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
  • 452
  • 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
  • 28,148
  • 6
  • 56
  • 87
Human-Compiler
  • 11,022
  • 1
  • 32
  • 59
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
  • 158,093
  • 24
  • 286
  • 300