C++ : Does char pointer to std::string conversion copy the content?

Subway picture Subway · May 8, 2013 · Viewed 8.6k times · Source

When I convert a char* to std::string using the constructor:

char *ps = "Hello";
std::string str(ps);

I know that std containers tend to copy values when they are asked to store them. Is the whole string copied or the pointer only? if afterwards I do str = "Bye" will that change ps to be pointing to "Bye"?

Answer

Violet Giraffe picture Violet Giraffe · May 8, 2013

std::string object will allocate internal buffer and will copy the string pointed to by ps there. Changes to that string will not be reflected to the ps buffer, and vice versa. It's called "deep copy". If only the pointer itself was copied and not the memory contents, it would be called "shallow copy".

To reiterate: std::string performs deep copy in this case.