Search code examples
c++boostconstructorshared-ptrtemporary

Temporary boost::shared_ptr when passing to constructor of superclass


In a library project I have a low level BaseClass class that takes a boost::shared_ptr to some object as an argument in the constructor, like this.

class SomeClass {
  public:
    SomeClass(int i);
};

class BaseClass {
  private:
    boost::shared_ptr<SomeClass> someObject;
  public:
    BaseClass(boost::shared_ptr<SomeClass> object) : someObject(object) {}
};

I now want to create a derived class that initialises the shared_ptr with a new object, created from values passed to the constructor of the derived class.

class DerivedClass : public BaseClass {
  public:
    DerivedClass(int i) 
      : BaseClass(boost::shared_ptr<SomeClass>(new SomeClass(i))) 
    {}
};

The problem is that this creates a temporary shared_ptr object. According to the best practices in the documentation, this should be avoided where possible because it can result in memory leaks. http://www.boost.org/doc/libs/1_56_0/libs/smart_ptr/shared_ptr.htm#BestPractices

However, I don't see how I could create a named shared_ptr object without modifying the signature of my constructors and therefore changing the API of my library.

Is there a way out of this?


Solution

  • The best practices page suggests a second approach, and that's what you should do: use make_shared.