The std line should crash but not

I have a class:

class A {
  public:
  string B;
};

and then the code:

A a1;
a1.B = "abc";

printf("%p.\n", a1.B.c_str());

A a2(a1);

printf("%p.\n", a2.B.c_str());

The c_str of both instances refer to the same place (as I understand it, the copied constructor is copied and the string internally stores data in char *, and the pointer is copied.

but the question is why is this code not crashing? a1 and a2 are stack variables, when deconstructing them, line B will also be deconstructing, will the internal char * from these lines (which points to the same memory location) be deleted twice? Isn't that a double deletion that should cause a crash? btw I disabled gcc optimizations, and valgrind doesn't show anything either.

+4
source share
4 answers

, . std::string .

: ++, , ( ), , ++ 11. -, GCC, .

+13

GCC 4. *

, , . 0, . , (boost ++ 11).

, , , , .

+3

,

. ++ "must crash". undefined, . , undefined.

c_str ( , , char *, .

std::string. , , , .

, , , copy-on-write "COW", ++ 11. GCC .

. , GCC 5:

std::string , .

- , , , Visual ++ std::string. -, , std::string , , GCC, , Visual ++.

, ?

std::string , .

, .

a1 a2 - ,

( , " " ).

B , char * ( ) ?

std::string , . COW, , , .

GCC, std::string, , . , , , . , GCC:

~basic_string()
{ _M_rep()->_M_dispose(this->get_allocator()); }

_M_dispose ( ), , .

:

a std::string , , ?

+2

, , .

-2

All Articles