dimba
dimba

Reputation: 27571

shared_ptr as class member

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.

Upvotes: 9

Views: 10758

Answers (4)

ereOn
ereOn

Reputation: 55726

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 ?!


Update

If C++11 is an option, you should probably better use std::unique_ptr instead which has less overhead and is movable.

It depends on how you want your enclosing class to behave in regards to copy.

Upvotes: 8

Mark Ransom
Mark Ransom

Reputation: 308091

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.

Upvotes: 1

Basilevs
Basilevs

Reputation: 23896

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.

Upvotes: 2

Nikko
Nikko

Reputation: 4252

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.)

Upvotes: 0

Related Questions