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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值