views:

161

answers:

4

It's common to declared contained objects as a pointers to that class, while "forward declarating" them in header file. This in order to reduce physical dependencies in code.

For example

class B;  // forward declaration   

class A {
   private:
      B* pB;
};

Would it be good idea to declare such a member as shared_ptr, instead of naked pointer?

I would prefer scoped_ptr, but AFAIK it it won't be in standard.

A: 

In the case of a composition, yes it is a good idea if you don't want physical dependency. Then your B will be destroyed automatically when A is.

If you don't mind physical dependency, you can just hold the data member by value.

(You can also check for the pimpl idiom if physical dependency is a problem.)

Nikko
A: 

Yes you can (should ?).

This is a common practice. As you stated it avoids the need to explicitely call delete().

You can go even further. Here is an example:

class RSAKey
{
  public:

    RSAKey();

  private:

    shared_ptr<RSA> d_rsa; // A pointer to a RSA structure from OpenSSL
}

Which I initialize like this:

RSAKey::RSAKey()
{
  RSA* rsa = RSA_generate_key(1024, 1, NULL, NULL);

  if (NULL == rsa) throw DummyException();

  d_rsa.reset(rsa, RSA_free); // Note the specific release method.
}

When d_rsa will no longer be used, an automatic call to RSA_free() will occur. Isn't that cool ?!

ereOn
automatic member deallocation is exactly my question :)
dimba
+2  A: 

If this pointer is not passed out of your class impelementation and execution speed is crucial, use scoped_ptr instead of shared_ptr. shared_ptr has an overhead.

Basilevs
I believe scoped_ptr is not in incomming C++0X standard.
dimba
@idimba, `unique_ptr` is the C++ version of it, which is also movable.
Johannes Schaub - litb
A: 

Using a shared_ptr would allow you to pass ownership to another object, so that it doesn't get destroyed when your outer object is destroyed. You state that this won't be a concern in this particular case.

The only advantage a smart pointer will have is that you won't need to remember to put a delete pB in your destructor. That may be enough advantage for most people.

When you don't need to worry about ownership issues, even an auto_ptr will be good enough.

Mark Ransom