简体   繁体   中英

Initialization of a static const variable

I am bit confused about 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 is declared as static and const , shouldn't this be initialized only once and keep its initial value until the process is completed? According to this reasoning, I was expecting the following output:

Hello
Hello

But I got:

Hello
Nooo

Can you clarify why the value of the variable c has been modified between two function calls even though it is a const variable?

Your program has undefined behavior .

When you pass "hello" to test , a temporary std::string object is created, and from that string c is constructed (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. Using it again is undefined behavior.

In your case, the second temporary std::string object's data has the exact same memory address as the first one, so c points to that data. This is not guaranteed whatsoever.

You have Undefined Behaviour in your code so those results may vary. The UB is because call test("Hello"); creates a temporary which then you assign to static local variable. This temporary is destoryed after a call ends, so the pointer in test function is dangling. If you use it then you have undefined behaviour.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM