Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing std::shared_ptr with std::make_shared having an std::array as argument

I do not understand why this works fine:

std::array<double, 2> someArray = {0,1};
std::shared_ptr<MyClass> myobj = std::make_shared<MyClass>(someArray);

But this does not work:

std::shared_ptr<MyClass> myobj = std::make_shared<MyClass>({0,1});

Compiler says:

too many arguments to function ‘std::shared_ptr< _Tp> std::make_shared(_Args&& ...)
...
candidate expects 1 argument, 0 provided

Question: Can someone clarify why this happens and if there is any way I can fix the second approach without defining an extra variable?


Edit: Example of MyClass:

#include <memory> //For std::shared_ptr
#include <array>
#include <iostream>

class MyClass{
  public:
    MyClass(std::array<double, 2> ){
      std::cout << "hi" << std::endl;
    };
};

like image 702
Puco4 Avatar asked Apr 12 '26 06:04

Puco4


1 Answers

Braced initializers {} can never be deduced to a type (in a template context). A special case is auto, where it is deduced to std::initializer_list. You always have to explictly define the type.

auto myobj = std::make_shared<MyClass>(std::array<double, 2>{0, 1});
like image 117
local-ninja Avatar answered Apr 14 '26 21:04

local-ninja