DevCoder
DevCoder

Reputation: 121

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

Upvotes: 3

Views: 8559

Answers (5)

Pete Becker
Pete Becker

Reputation: 76498

When you delete an object it's gone. Anything that refers to that object (pointer, reference) becomes invalid.

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

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

Ed Heal
Ed Heal

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

Sergey Kalinichenko
Sergey Kalinichenko

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.


* References are not pointers, though.

Upvotes: 5

Zdeslav Vojkovic
Zdeslav Vojkovic

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

Related Questions