Pointers
- Points to a memory address
- Can be reassigned
- Can be null or nullptr
- Access its contents by using a * in front of the pointer I.E. *ActorPtr
- Access the address like so ActorPtr
- You can change the address of the pointer like so ActorPtr = &Actor
- You can change the value of the pointer like so *ActorPtr = Actor
References
- Stores a memory address
- Cannot be reassigned
- Cannot be null and must be initialised
- You can access the contents of a reference like so ActorRef
- You can access the address of a reference like so &ActorRef
- Since a reference cannot be reassigned, you cannot change its memory address
- You can change the value of the reference like so ActorRef = Actor
The & And * Symbols In Context
When using a pointer and there is a * in front of it, the * allows you to access the content of the pointer, this is also known as dereferencing. An example of this is CopyOfActor = *ActorPtr. When using a variable/reference and a & is in front of it, you are accessing the address of the reference. For example, ActorAddress = &Actor.
However when both symbols have different meaning when used with a type to declare a variable. With the * symbol you are declaring a pointer to some type, for example, UActor* ActorPtr. This means you have created a pointer that will point to a UActor. With the & symbol you are declaring a reference to some type, for example, UActor &ActorRef. This mean you have creaated a refence to a UActor.
Example Demonstration Code
Visit - https://onlinegdb.com/ByP5XeNa4 and run the code.
Pointers Or References?
- The golden rule is to use references unless you can't
- References are newer and safer
- Pointers provide back-compatibility
- Pointers are more powerful
- Pointers are more dangerous
"With Great Power Comes Great Responsibility" - Uncle Ben