I have a class with a (non smart) pointer to an interface object (lets call it pInterface) and I am building a nested class which also needs access to that interface. I am going to get around this by passing the pointer to the interface into the constructor of the nested class like so:
CNestedClass someClass( pInterface, ... );
However I am unsure of the best way of storing this pointer in the nested class. I could use:
1) A scoped (or other smart) pointer (to the original object)
2) A pointer to a pointer
What would you guys suggest and why?
EDIT: I should clarify - the nested class will need to call methods on the interface object, however it does not create it (or modify the object 'pointed' to ), the parent class is responsible for that.
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 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;
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With