c++ - Initialization of a static const variable -
i bit confused following c++ code:
#include <iostream> using namespace std; void test(const string& str) { static const char * const c = str.c_str(); cout << c << endl; } int main(int argc, char* argv[]) { test("hello"); test("nooo"); return 0; }
since variable c
declared static
, const
, shouldn't initialized once , keep initial value until process completed? according reasoning, expecting following output:
hello hello
but got:
hello nooo
can clarify why value of variable c
has been modified between 2 function calls though const
variable?
your program has undefined behavior.
when pass "hello"
test
, temporary std::string
object created, , string c
constructed (which pointer data of string object).
when function call ends, temporary std::string
object destroyed, , c
becomes dangling pointer. using again undefined behavior.
in case, second temporary std::string
object's data has exact same memory address first one, c
points data. not guaranteed whatsoever.
Comments
Post a Comment