C ++ scopes and pointers

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 area bracket, the code will print

hello
goodbye

What exactly happens when I leave the first scope that the pointer to the first line now points to the second?

+5
source share
4 answers

Stored pointers become dangling pointers after the scope and any attempt to read what they point in order to infer undefined behavior.

+7
source

What happens to undefined behavior, as it sgoes out of scope at the time you referred to it in an operator call cout<<.

, s ss ++. , , , , .

+3

, s ss. , ; ++ - , , , - undefined.

+3

, : undefined. .

+2

All Articles