assigning string::c_str() to a const char* when th

2020-04-06 01:21发布

问题:

I have a doubt on basic C++ usage. The code below, compiled with gcc/LInux, prints out correctly.

The string test goes out of scope so also its c_str() value should be invalid isn't it? Am I wrong or do I have misunderstood the const char*meaning?

   #include <iostream>
   int main(){
     const char* a = "aaaa";
       std::cout << a;
       { std::string test("bbbb");a=test.c_str();}
       std::cout << a;
       a = "cccc";
       std::cout << a;
   }


   aaaabbbbcccc
   // print out without any problem

回答1:

You're right, your code is not valid since it uses an object whose lifetime has already ended. It works "by accident", you cannot rely on that.



回答2:

It could be because of string pooling. Neverthless, it is Undefined behavior. We should not use the c_str() output once the string goes out of scope.



回答3:

While the string object goes out of scope, the memory pointed to by a will still be there. I don't think the standard says anything about clearing the actual memory locations when a string is destructed.



回答4:

The program invokes undefined behavior. When a program does that, the compiler is free to do whatever it wishes, including creating a program that works as one might expect.

The likely reason why it works the way it does is as follows. At the end of the inner block, test goes out of scope and its destructor is run. This frees the block of memory used to hold the actual string for other uses, but the memory is not cleared (that would be a waste of time). The memory thus freed is not, for one reason or another, reused before bbbb is printed out.

(Note that the cccc assignment and printout is valid.)



回答5:

Because test goes out of scope, what you are doing is undefined behavior. Do not make assumptions about how it will function.

It could just as well segfault and the behavior will still be correct. UB is UB.