Initializing shared_ptr member variable, new vs make_shared?

12,771

Solution 1

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.

Solution 2

In this case, using make_shared is not just allowed, but it is better to use it. If you use new, it will allocate memory for your Customer somewhere and then memory for your shared_ptr somewhere else, storing both strong and weak references (for weak pointers and shared pointers). If you use the make_shared you would have only one place in memory with everything and therefore only one new.

I'm not sure that I was really clear, this was the purpose of the GotW #89, read it, it is well explained there.

Share:
12,771
User
Author by

User

Updated on June 05, 2022

Comments

  • User
    User almost 2 years

    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?

  • Matthieu M.
    Matthieu M. about 12 years
    Regarding the friendship issue, is there any mention in the Standard of the particular function to use as friends ? I could well envision some implementation delegating this work to helper functions...
  • Nicol Bolas
    Nicol Bolas about 12 years
    @MatthieuM.: I was kinda wondering the same thing, which is why I said "may be able". I've asked over at comp.std.c++; we'll see what they have to say about it. If not, I think it might make for a decent defect report.