Subway
Subway

Reputation: 5716

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

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"?

Upvotes: 16

Views: 10604

Answers (2)

parkydr
parkydr

Reputation: 7784

str will contain a copy of ps, changing str will not change ps.

Upvotes: 5

Violet Giraffe
Violet Giraffe

Reputation: 33579

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.

Upvotes: 36

Related Questions