The use a pointer to a pointer is if either class may alter the value of the pointer - e.g. by deleting the existing object and replacing it with a new one. This allows both classes to still use the same object by dereferencing the pointer-to-pointer.
If not your concern is ensuring the object remains valid throughout the lifetime of both classes.
- If the nested class lives shorter you don't really have to worry.
- If it's the same, provided you clean-up in the correct order (e.g. nested class first, object later) then again, you don't have to worry
- If the nested class could persist after the owner is destroyed then you must implement a way to ensure the object also persists.
If you need to ensure the lifetime of the object it could be done via reference counting-semantics, either manually or through a smart-pointer interface.
For a smart pointer then boost::shared_ptr would be a good choice. shared_ptr allows the ownership of an object to be shared amount multiple pointers. When the last shared_ptr goes out of scope, the object is deleted.
(note this is not the case with auto_ptr, where an object are exclusively owned).
Things to be aware of;
- When using boost::shared_ptr be sure the nested class has a copy of the shared_ptr and not a reference/pointer.
- std::auto_ptr behaves quite differently, objects are exclusively owned and not shared
- boost::shared_ptr can only work with heap objects, e.g pointers returned from a call to 'new'
Example:
typedef boost::shared_ptr<Interface> shared_interface;
class NestedClass
{
shared_interface mInterface; // empty pointer
}
void NestedClass::setInterface(shared_interface& foo)
{
mInterface= foo; // take a copy of foo.
}
void ParentClass::init( void )
{
// mInterface is also declared as shared_interface
mInterface = new Interface();
mNestedClass->setInterface(mInterface);
}