I have the following code:
using namespace std;
vector<string*> v;
{
string s = "hello";
v.push_back(&s);
}
{
string ss = "goodbye";
v.push_back(&ss);
}
cout << v.at(0)->c_str() << endl;
cout << v.at(1)->c_str() << endl;
which prints
goodbye
goodbye
if I remove the scope parenthesis the code will print
hello
goodbye
What exactly happens when I leave the first scope, that the pointer to the first string now points to the second one?
The stored pointers become dangling pointers after the scope and any attempt to read what they point to yields undefined behavior.
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