Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 279
Subway Avatar asked May 08 '13 11:05

Subway


2 Answers

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.

like image 120
Violet Giraffe Avatar answered Oct 02 '22 13:10

Violet Giraffe


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

like image 36
parkydr Avatar answered Oct 02 '22 15:10

parkydr