assigning string::c_str() to a const char* when the string goes out of scope

后端 未结 5 1701
北恋
北恋 2021-01-18 06:22

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_

5条回答
  •  日久生厌
    2021-01-18 06:56

    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.)

提交回复
热议问题