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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With