Some advantages of owning an instance (class B { A a; };):
- No need to worry about creation and destruction of abecause it happens automatically.
- No need to worry that amight be a dangling or null pointer.
- Memory locality: alives where instances ofBlive. If you have a large array ofBs and access eachB'sAin turn, this could make a significant speed difference.
- Memory efficiency: no storage for a pointer is needed.
To make a huge sweeping generalization, one could say that this approach is faster and safer.
Some advantages of owning a pointer (class B { A *a; };):
- Polymorphism: acan actually point to a subclass ofA.
- acan be reassigned without needing to copy an instance of- A.
- acan live independently of- Bor even be owned by another object entirely.
- acan be null, freeing up memory if it's not always needed.
To make another huge sweeping generalization, one could say that this approach is more flexible.