C++ reference on deleted objects

c++, object, reference

Solution

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.

Problem

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 ```

Original source