Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std string should crash but doesn't

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.

like image 943
Zhani Baramidze Avatar asked Dec 04 '22 00:12

Zhani Baramidze


1 Answers

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.

like image 145
Mark Ransom Avatar answered Dec 06 '22 15:12

Mark Ransom