Values by reference: & vs. *


What is the difference in the meaning of the following two statements?




AudioSource& is a reference, AudioSource* is a pointer. Both are used to point/refer to some other object. References are often used when the passed object can not meaningfully be non-existent.

The reference AudioSource& references an object “living” somewhere else, so you cannot delete it.

AudioSource source; // is created on the stack, will be automatically deleted when the scope ends i.e. { is closed
AudioSource* sourcePtr = &source;  // a pointer to the source, created by the address operator
AudioSource& sourceRef = source;   // no object is created. If used, after 'source' is deleted, your code will crash
AudioSource& sourceRef2 = *sourcePtr; // a reference can be created by dereferencing a pointer

// an object is created on the heap memory.
AudioSource* source2 = new AudioSource();
// Because it is easy to forget to call delete, this should no longer be used!

// use RAII instead:
ScopedPointer<AudioSource> source3 = new AudioSource(); // source3 is a pointing object on the stack pointing to the pointee (AudioSource) on the heap memory. 
// If the ScopedPointer goes out of scope, the pointee is automatically deleted.