Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::move on std::string garantee that .c_str() returns same result?

I want to provide zero-copy, move based API. I want to move a string from thread A into thread B. Ideologically it seems that move shall be able to simply pass\move data from instance A into new instance B with minimal to none copy operations (mainly for addresses). So all data like data pointers will be simply copied no new instance (constructed via move). So does std::move on std::string garantee that .c_str() returns same result on instance before move and instance created via move constructor?

like image 658
DuckQueen Avatar asked Apr 22 '15 19:04

DuckQueen


2 Answers

No. There's no requirement for std::string to use dynamic allocation or to do anything specific with such an allocation if it has one. In fact, modern implementations usually put short strings into the string object itself and don't allocate anything; then moving is the same as copying.

It's important to keep in mind that std::string is not a container, even though it looks very similar to one. Containers make stronger guarantees with respect to their elements than std::string does.

like image 148
Kerrek SB Avatar answered Oct 19 '22 11:10

Kerrek SB


No, it's not guaranteed.

Guaranteeing it would basically prohibit (for one example) the short string optimization, in which the entire body of a short string is stored in the string object itself, rather than being allocated separately on the heap.

At least for now, I think SSO is regarded as important enough that the committee would be extremely reluctant to prohibit it (but that could change--when the original C++98 standard was written, they went to considerable trouble to allow copy-on-write strings, but they are now prohibited).

like image 33
Jerry Coffin Avatar answered Oct 19 '22 13:10

Jerry Coffin