I have a class:
class A {
public:
string B;
};
and then a code:
A a1;
a1.B = "abc";
printf("%p.\n", a1.B.c_str());
A a2(a1);
printf("%p.\n", a2.B.c_str());
c_str's of both instances refer to same place (this I understand, copy constructor copied A bit-by-bit, and string internally stores data in char*, and pointer got copied.
but the question is, why doesn't this code crash? a1 and a2 are stack variables, when desconstructing them string B's will also get deconstructed, won't internal char* of those strings (that point to same memory location) get deleted twice? isn't it double delete, which should cause crash? btw I disabled gcc optimizations and valgrind doesn't show anything as well.
No, the pointer did not get copied. The copy constructor of std::string
creates a new buffer and copies the data from the buffer of the other string.
Edit: the C++ standard used to allow copy-on-write semantics, which would share the pointer (and would require reference counting to go along with it), but this was disallowed starting with C++11. Apparently there were versions of GCC which did this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With