Using a pointer to a pointer is if a class can change the value of a pointer - for example. deleting an existing object and replacing it with a new one. This allows both classes to still use the same object by dereferencing a pointer to a pointer.
If you are not concerned that the object remains valid throughout the life of both classes.
- If the nested class lives shorter, you really don't need to worry.
- If this is the same, if you clean in the correct order (for example, a nested class first, an object later), then again you will not have to worry
- If the nested class can persist after the owner is destroyed, you must implement a way to ensure that the object is saved.
If you need to ensure the lifetime of the object, this can be done using the semantics of links, either manually or through the interface of a smart pointer.
For a smart pointer, then boost :: shared_ptr would be a good choice. shared_ptr allows you to own an object that is the total number of multiple pointers. When the last shared_ptr goes out of scope, the object is deleted.
(note that this does not apply to auto_ptr, where the object belongs exclusively).
What you need to know
- When using boost :: shared_ptr, make sure the nested class has a copy for shared_ptr and not a link / pointer.
- std :: auto_ptr behaves in a completely different way, objects belong exclusively and are not used.
- boost :: shared_ptr can only work with heap objects, for example, pointers returned from a call to "new"
Example:
typedef boost::shared_ptr<Interface> shared_interface; class NestedClass { shared_interface mInterface;
source share