Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 818
dimba Avatar asked May 10 '10 05:05

dimba


People also ask

Can shared_ptr be Nullptr?

A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .

What is a shared_ptr in C++?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.

Should I use shared_ptr or unique_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

Can shared_ptr be copied?

The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr . Constructing a new shared_ptr using the raw underlying pointer owned by another shared_ptr leads to undefined behavior.


1 Answers

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.

like image 175
ereOn Avatar answered Sep 30 '22 13:09

ereOn