How to call std::make_shared in case of initializer_list arguments?

636 Views Asked by At

I am trying to use std::make_shared for object construction on heap in my program instead of new, but when object constructor is supplied with initializer list the simple replacement does not work and I have to manually specify exact type:

#include <vector>
#include <memory>

struct A
{
    A( std::vector<int> ) {}
};

int main()
{
    std::shared_ptr<A> p{ new A({1}) }; //Ok
//    std::shared_ptr<A> q = std::make_shared<A>({1}); //Compiler error
    std::shared_ptr<A> q = std::make_shared<A>(std::initializer_list<int>{1}); // Ok, but too wordy
}

Is there a way to use std::make_shared in such situation and keep the code compact (avoid explicit type of the initializer list)?

1

There are 1 best solutions below

0
AudioBubble On

It makes sense that it would not compile. struct A does not take initializer list. And there is no implicit conversion available.

you can do following though: std::make_shared<AA>(std::vector<int>{ 1 });