Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isn't a std::string a std::vector<char>?

In c++ primer 5th, 9.2.5. Assignment and swap, I read about this:

The fact that elements are not moved means that, with the exception of string, iterators, references, and pointers into the containers are not invalidated. They refer to the same elements as they did before the swap.

So, why is string a exception? I always think that string is a vector, isn't that true?

like image 261
cong Avatar asked Jan 29 '26 02:01

cong


1 Answers

The very wording you cite demonstrates that strings aren't vectors. When you swap two vectors, iterators remain valid and point into the new vectors. There is no analogous requirement on strings. This allows strings to use small-buffer optimizations.

It may be more appropriate to compare basic_string and vector, because those are both templates that are parametrized on element type and allocator. This shows further differences: basic_string may only be specialized for literal types. And basic_string also takes a third parameter, the traits, which determine how comparison is done.

What strings have in common with vectors is that they store the data contiguously.

like image 54
Kerrek SB Avatar answered Jan 31 '26 22:01

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!