Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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") 
like image 764
Narek Avatar asked Aug 17 '15 12:08

Narek


People also ask

Why should we use make_ shared?

As well as this efficiency, using make_shared means that you don't need to deal with new and raw pointers at all, giving better exception safety - there is no possibility of throwing an exception after allocating the object but before assigning it to the smart pointer.

What is std :: Make_shared?

std::make_sharedAllocates and constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr<T> that owns and stores a pointer to it (with a use count of 1). This function uses ::new to allocate storage for the object.


1 Answers

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});  } 
like image 101
dau_sama Avatar answered Sep 18 '22 08:09

dau_sama