string - C++11, 5 of n

(1) Gotchas
in C++98, string literals, such as 'hello', was changed to const char*. Sticktly speaking, the original type of a literal such as 'hello' is  const char[6]. But this type automatically converts(decays) to const char*, so we almost always use (and see) const char* in declarations. However, When working with templates, the difference might matter because for reference template parameters, decay doesn't occur unless type trait std::decay() is used.

The type and value of “npos” are a big pitfall for the use of strings. Be very careful that you always use string::size_type, not int or unsigned, for the return type when you want to check the return value of a find function. Otherwise, the comparison with string::npos might not work.

template <typename charT, typename traits = char_traits<charT>, typename Allocator = allocator<charT> >
class basic_string {
public:
    typedef typename Allocator::size_type size_type;
    ...
    static const size_type npos = -1;
    ...
};

For example:
int idx = s.find("hi"); // assume npos is returned
if(idx == string::npos) // ERROR: comparison might not work think...there is type conversion here
{
    ...
}

We should code as below:
string:size_type idx = s.find("hi");
if(idx == string::npos)
{
    ...
}

(2) Main new features in C++11
a. Strings now provide convenience functions to convert strings to numeric values and vice versa
b. Strings now support move semantics and initializer list
c. u16string and u32string are predefined (plus string and wstring)
d. Strings are now indirectly required to provide an end-of-string character (’\0’ for string) because for a string s, s[s.length()] is always valid and s.data() returns the characters including a trailing end-of-string character
e. Reference-counted implementations of string classes are no longer supported
f. Strings now provide front() and back() to access the first or last element and shrink_to_fit to shrink capacity



你可能感兴趣的:(C++,String,Parameters,templates,Literals)