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;
}
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;
}
It is unsafe.
Any use of a pointer or reference to a member of a destroyed object is undefined behavior.
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.