16

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

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
Subway
  • 5,286
  • 11
  • 48
  • 59

2 Answers2

34

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.

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
  • 1
    Can you add a source for that? – Philipp Ludwig Dec 07 '18 at 12:29
  • 2
    @PhilippLudwig The Standard (N4140, §21.4-2) says *The member functions of `basic_string` use an object of the `Allocator` class passed as a template parameter to allocate and free storage for the contained char-like objects.* – ynn Feb 05 '20 at 14:41
5

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

Azeem
  • 11,148
  • 4
  • 27
  • 40
parkydr
  • 7,596
  • 3
  • 32
  • 42