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