Reputation: 121
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
Upvotes: 3
Views: 8559
Reputation: 76498
When you delete an object it's gone. Anything that refers to that object (pointer, reference) becomes invalid.
Upvotes: 1
Reputation: 110768
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.
Upvotes: 9
Reputation: 60037
The &
can either mean a reference (as in the declaration asyncCall(&Foo)
- you misses the data types for the return value and parameters) or takes the address of (as in asyncCall(&foo)
).
It would also help to have some code that nearly resembles C++ and better still compiles.
Upvotes: 0
Reputation: 727047
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.
Upvotes: 5
Reputation: 14591
Besides the fact that your samples are not even close to proper C++ and none of it would compile, it is never OK to operate on deleted objects
Upvotes: 1