Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reference on deleted objects

I'm learning C++ (coming from iOS) and I want to understand the pointer / reference usage.

Is is correct to work with references on objects when they are deleted? Or will the referenced variable also get deleted?

Example:

Class Foo {
}

Class Faa{
   asyncCall(&Foo)
}

1.

// ...
Foo *foo = new Foo();
faa->(asyncCall(&foo);
delete foo;
// ...

2.

// ...
Foo *foo = new Foo();
Foo& refFoo = foo;
delete foo;

// do something with refFoo
like image 358
DevCoder Avatar asked Aug 29 '26 04:08

DevCoder


2 Answers

Since your code samples are gibberish, I'll pose my own:

Foo* foo = new Foo();
Foo& ref = *foo;
delete foo;

// Use refFoo

This is bad. A reference simply refers to an object created elsewhere. In this example, *foo and ref are exactly the same object. As soon as you destroy that object, by doing delete foo;, ref is left dangling. It's referring to an object that doesn't exist any more. Accessing it will result in undefined behaviour.

like image 195
Joseph Mansfield Avatar answered Aug 31 '26 20:08

Joseph Mansfield


A reference in C++ is not the same as a reference in Java, C#, or other garbage-collected languages: for most practical purposes, you can think of a C++ reference as a pointer that you don't need to dereference*. Creating a reference to an object does not prolong its life time. That's why it's no more OK to access a deleted object through a reference than it is to access a deleted object through a second pointer: it is undefined behavior.


* References are not pointers, though.
like image 29
Sergey Kalinichenko Avatar answered Aug 31 '26 20:08

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!