Search code examples
c++shared-ptr

Can I use std::make_shared with structs that don't have a parametric constructor?


Say I have a struct like this:

struct S
{
int i;
double d;
std::string s;
};

Can I do this?

std::make_shared<S>(1, 2.1, "Hello")

Solution

  • No you can't, you have to define your own constructor for being able to do it.

    #include <iostream>
    #include <memory>
    #include <string>
    
    struct S
    {
        S(int ii, double dd)
        : i(ii)
        , d(dd)
        { }
      int i;
      double d;
    };
    
    int main()
    {
     // S s{1, 2.1};
      auto s = std::make_shared<S>(1, 2.1);
      //or without constructor, you have to create manually a temporary
      auto s1 = std::make_shared<S>(S{1, 2.1});
    
    }