我可以将 std::make_shared 用于没有参数构造函数的结构吗?
Can I use std::make_shared with structs that don't have a parametric constructor?
假设我有一个 struct
这样的:
struct S
{
int i;
double d;
std::string s;
};
我可以这样做吗?
std::make_shared<S>(1, 2.1, "Hello")
不可以,您必须定义自己的构造函数才能执行此操作。
#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});
}
假设我有一个 struct
这样的:
struct S
{
int i;
double d;
std::string s;
};
我可以这样做吗?
std::make_shared<S>(1, 2.1, "Hello")
不可以,您必须定义自己的构造函数才能执行此操作。
#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});
}