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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With