Search code examples
c++objectobject-lifetime

Lifetime of object created without 'new' assigned to pointer


Let's say we have:

struct A
{
    int data;
};

int main( void )
{
  {
    A a;
    a.data = 4;
  }

  cout << "Hello World" << endl;
  return 0;
}

I understand that object created without new is stored on the stack and is destructed automatically upon exit from the scope in which it is defined. So by the time it gets to execute line 13 the object a should not exist.

The second case:

struct A
{
    int data;
};

int main( void )
{
 A * b;
  {
    A a;
    a.data = 4;
    b = &a;
  }

  cout << b->data << endl;
  return 0;
}

The question is when will be the object destroyed if I assign the address of a inside the scope to a pointer? Since I can print the data value of that object outside of the scope that means the object must still exist.


Solution

  • No, it means that you have encountered undefined behavior so any conclusion that you could deduce is irrelevant.

    The address stored in b won't point to any valid data after closing the scope, period.