Initializing a Static Constant Variable

I am a bit confused in the 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 the variable c declared as static and const , shouldn't it be initialized only once and keep its initial value until the process is complete? According to these considerations, I expected the following output:

 Hello Hello 

But I got:

 Hello Nooo 

Can you explain why the value of the variable c was changed between two function calls, even if it is a const variable?

+6
source share
2 answers

Your program has undefined behavior .

When you pass "hello" to test , a temporary std::string object is created, and c is created from this string (which is just a pointer to the data of the string object).

When the function call ends, the temporary std::string object is destroyed, and c becomes a dangling pointer. Use this undefined behavior again.

In your case, the second temporary std::string object has the same memory address as the first, so c points to this data. This is not guaranteed.

+14
source

You have Undefined Behavior in the code so that these results may differ. UB is that the call to test("Hello"); creates a temporary one, which is then assigned to a static local variable. This time is destroyed after the call ends, so the pointer in the test function hangs. If you use it, you have Undefined behavior.

It is possible that the memory manager is reusing the same memory area, so you see Hello and Nooo in your results.

+1
source

All Articles