3

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)?

Fedor
  • 17,146
  • 13
  • 40
  • 131
  • 1
    Does this answer your question? [std::shared\_ptr and initializer lists](https://stackoverflow.com/questions/11820981/stdshared-ptr-and-initializer-lists) – Igor R. Jul 03 '21 at 09:13
  • 2
    I wonder why `make_shared` doesn't have an extra overload with `initializer_list` as the first parameter, like e.g. [the constructor of `std::optional`](https://en.cppreference.com/w/cpp/utility/optional/optional) (#7) does. – HolyBlackCat Jul 03 '21 at 09:15

1 Answers1

0

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 });