0

Can I use ref after object deletion like shown in this example or is it unsafe?

struct Object
{
    int value;
};

void function()
{
    Object* object = new Object();
    int& ref = object->value;
    delete object;
    ref = 50;
}
Michaelt LoL
  • 400
  • 5
  • 10

2 Answers2

6

It is unsafe.

Any use of a pointer or reference to a member of a destroyed object is undefined behavior.

François Andrieux
  • 26,465
  • 6
  • 51
  • 83
Human-Compiler
  • 10,027
  • 27
  • 49
6

No, you cannot. Object::value is a subobject of Object. Destroying *object also destroys object->value. After delete object;, the reference no longer refers to a valid object and any usage of the value of ref is undefined behavior.

cdhowie
  • 144,362
  • 22
  • 272
  • 285