Initializing shared_ptr member variable, new vs make_shared?

User picture User · Apr 24, 2012 · Viewed 12k times · Source

When initializing a shared_ptr member variable:

// .h
class Customer
{
public:
  Customer();

private:
  std::shared_ptr<OtherClass> something_;
}

// .cpp
Customer():
  something_(new OtherClass())
{
}

vs.

Customer():
  something_(std::make_shared<OtherClass>())
{
}

Is the make_shared version allowed? I always seem to see the first version, which is preferred?

Answer

Nicol Bolas picture Nicol Bolas · Apr 24, 2012

The only times when make_shared is not allowed are:

  1. If you're getting a naked pointer allocated by someone else and storing it in shared_ptr. This is often the case when interfacing with C APIs.
  2. If the constructor you want to call is not public (make_shared can only call public constructors). This can happen with factory functions, where you want to force users to create the object from the factory.

    However, there are ways to get around this. Instead of having a private constructor, have a public constructor. But make the constructor take a type with can only be constructed by those with private access to the class. That way, the only people who can call make_shared with that object type are those with private access to the class.

So yes, you can do this.