1

I noticed that I cannot instantiate an object as a make_shared parameter (see example bellow). Since I am not really experienced with templates, the definition of the make_shared template< class T, class... Args > shared_ptr<T> make_shared( Args&&... args ); does not reveal to me why make_shared({0}) fails.

Can someone explain why this happens?

class Alpha
{
    int mValue;
    bool mBool;
public:
    Alpha(int value, bool lbool) :mValue(value), mBool(lbool){}
};
class Beta
{
    Alpha mAlpha;
public:
    explicit Beta(Alpha alpha): mAlpha(alpha){}
};

int main()
{
    Alpha a{0, true};
    Beta b1(1, a); // ok
    Beta b2(1, {0, true}); //ok
    auto pB1 = std::make_shared<Beta, Alpha>({ 0, true }); // ok
    auto pB2 = std::make_shared<Beta>({ 0, true }); // make_shared does not take 1 arguments

     auto pB3 = std::make_shared<Beta>(1, a); // ok
     auto pB4 = std::make_shared<Beta>(1, {0, true}); // Err:  make_shared does not take 2 arguments
     auto pB5 = std::make_shared<Beta>(1, Alpha{0, true}); // ok
     auto pB6 = std::make_shared<Beta>(1, Alpha{ 0, true }); // ok
     auto pB7 = std::make_shared<Beta, Alpha>(1, {0, true }); // Err: make_shared does not take 2 arguments
}

*edit1: added an extra property in Alpha

*edit2: added new cases, still am not sure why pB7 fails but pB1 can some one explain that?

wxkin
  • 43
  • 1
  • 8
  • Not sure what compiler you are using but in g++ `Beta b2({0});` is a error. – NathanOliver Mar 29 '17 at 18:45
  • If it isn't clear, the 'intended' way to write what you want is `std::make_shared(0);` – Pubby Mar 29 '17 at 18:50
  • @NathanOliver Tried both with gcc-arm-linux-gnueabi 4:4.6 and Visual C++ 14.0 – wxkin Mar 29 '17 at 18:59
  • @Pubby that is wrong. 0 is an `int`. B has not constructor accepting any `int`s – wxkin Mar 29 '17 at 19:03
  • `Alpha(int)` was not `explicit` and so `std::make_shared(0);` was equivalent to `Beta(Alpha(0))` – Pubby Mar 29 '17 at 19:10
  • @Pubby Yeah I see your point, that's why I updated the example to have two properties. As show in the answer of the similar question, the solution is `auto p = std::make_shared({ 0, true }); ` – wxkin Mar 29 '17 at 19:17

0 Answers0