Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to a Pointer question

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.

like image 999
Konrad Avatar asked Jan 24 '23 19:01

Konrad


1 Answers

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;

  1. When using boost::shared_ptr be sure the nested class has a copy of the shared_ptr and not a reference/pointer.
  2. std::auto_ptr behaves quite differently, objects are exclusively owned and not shared
  3. 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);
}
like image 54
Andrew Grant Avatar answered Jan 31 '23 22:01

Andrew Grant