Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 and C++03 differs in support for small string optimization for std::string?

In the compatibility appendix of the C++11 standard, one of the change from C++03 to C++11 is described as below:

C.2.11 Clause 21: strings library
21.4.1
Change: Loosen basic_string invalidation rules
Rationale: Allow small-string optimization.
Effect on original feature: Valid C++ 2003 code may execute differently in this International Standard. Some const member functions, such as data and c_str, no longer invalidate iterators.

The iterator invalidation rule of std::string does have changed from C++03 to C++11 in that data() and c_str() is not allowed to invalidate iterators anymore, but I don't know how that leads to the rationale of "allow small-string optimization"? Wasn't SSO already allowed prior to C++11?


Two of the differences of std::string between C++11 and C++03 that I knew of before I came across that SSO notes in the compatibility appendix are:

  • Elements are guaranteed to be stored contiguously in C++11
  • COW implementation is not an option in C++11 (certain operations such as operator[] is not allowed to invalidate iterators)

I took C++11's non-invalidating guarantee of c_str() and data() as the direct result of the change towards contiguous storage. Now it seems there is some connection with SSO implementation, and I would like to know the detail of the behind-scene logic. Thanks.

like image 787
goodbyeera Avatar asked Mar 11 '14 10:03

goodbyeera


1 Answers

I believe you are misinterpreting the "Change": this is not referring to the invalidation rules of data and c_str, but rather those of swap.

This question gave me this idea, and I think I am correct when I read your quote and the linked question/answers.

Since basic_string's swap can invalidate iterators, one can implement a SSO. In C++03, basic_string was a reversible container, which means it had to comply with this requirement for swapping containers:

The expression a.swap(b), for containers a and b of a standard container type other than array, shall exchange the values of a and b without invoking any move, copy, or swap operations on the individual container elements.

I may be immensely wrong though, IANALL (I am not a language lawyer).

like image 162
rubenvb Avatar answered Oct 18 '22 07:10

rubenvb