Search code examples
c++constructorshared-ptrinitializer-list

Shared argument in constructor initializer list


I have this classes:

class A
{
public:
    A(std::shared_ptr<SomeClass> p);
private:
    std::shared_ptr<SomeClass> _p;
};

class B
{
public:
    B(std::shared_ptr<SomeClass> p);
private:
    std::shared_ptr<SomeClass> _p;
};

class Foo
{
public:
    Foo();
private:
    A _a;
    B _b;
};

Both constructor arguments from A and B share the same pointer reference shared_ptr. In this case:

  • How would be the best way of initializing Foo?

  • Is it still possible to use a initialization list in Foos constructor?

I am confused, because since both classes need the same shared_ptrinstance, I would have to store that pointer somewhere, and I don't think that is possible with initialization lists.

Also, if the initialization occurs in the body of the constructor, it implies that both A and B should have a move constructor, correct? Because I would have to do something like this:

Foo::Foo() //: Cannot use initializer list
{
    auto ptr = std::make_shared<SomeClass>(SomeClass());
    _a = A(ptr);
    _b = B(ptr);
}

Solution

  • Actually, I thought of a better solution. Create the shared_ptr, then delegate to a private constructor that will use it to construct _a and _b. (Credit to Zan Lynx for suggesting the use of a function parameter as temporary storage.)

    class Foo {
    public:
        Foo(): Foo(std::make_shared<SomeClass>()) {}
    private:
        Foo(std::shared_ptr<SomeClass> ptr): _a(ptr), _b(ptr) {}
        A _a;
        B _b;
    };