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

I want to provide a zero copy and transition API. I want to move a row from stream A to stream B. Ideologically, it seems that relocation should just transfer / move data from instance A to new instance B with minimal or no copy operations (mostly for addresses). This way, all data, such as data pointers, will simply be copied without a new instance (built by moving). So std :: move on std :: string ensures that .c_str () returns the same result in the instance before the move and the instance created with the move constructor?


source to share

3 answers


but if needed, the parameter should put the string in std::unique_ptr

. Personally, I would normally not rely on the c_str () value more than the local scope.

Example, on request:

#include <iostream>
#include <string>
#include <memory>

int main() {
    std::string ss("hello");
    auto u_str = std::make_unique<std::string>(ss);
    std::cout << u_str->c_str() <<std::endl;
    std::cout << *u_str <<std::endl;
    return 0;


unless you have make_unique (new in C ++ 14).

auto u_str = std::unique_ptr<std::string>(new std::string(ss));


Or just copy the whole implementation from the STL clause :

A perfect example on how to do it



Not. There is std::string

no need to use dynamic allocation or do anything specific with such allocation, if any. In fact, modern implementations usually put short strings in the string object itself and don't allocate anything; then moving will be the same as copying.

It is important to remember that std::string

it is not a container, although it looks very similar to one. Containers provide higher guarantees on their items than they std::string




No, this is not guaranteed.

By guaranteeing this, it will basically prohibit (in one example) the optimization of short strings, in which the entire chunk of a short string is stored in the string object itself, rather than separately allocated on the heap.

At least for now, I believe SSO is considered so important that the committee would be extremely reluctant to prohibit it (but that may change - when the original C ++ 98 standard was written, they faced significant problems to allow copy-on-write strings , but they are now prohibited).



All Articles