在std :: make_shared中使用c ++聚合初始化 [英] using c++ aggregate initialization in std::make_shared
问题描述
据我所知,以下代码构造了一个 Foo
类型的对象,然后将该对象移动到 std :: make_shared
Per my understanding, the following code constructs an object of type Foo
and then moves that object into the memory allocated by std::make_shared
struct Foo
{
std::string s;
int i;
char c;
};
int main(int argc, char* argv[])
{
auto foo = std::make_shared<Foo>(Foo{"hello", 5, 'c' });
}
是否可以将初始化初始化 Foo
直接放入 std :: make_shared分配的内存 code>?
Is it possible to aggregate initialize Foo
directly into the memory allocated by std::make_shared
?
推荐答案
您可以创建一个带有可变构造函数模板的适配器来转发参数,例如:
You could create an adapter with a variadic constructor template to forward the arguments, something like:
template<class T>
struct aggregate_adapter : public T {
template<class... Args>
aggregate_adapter(Args&&... args) : T{ std::forward<Args>(args)... } {}
};
然后您可以执行以下操作:
And then you can do:
auto foo = std::make_shared<aggregate_adapter<Foo>>("hello", 5, 'c');
由于 aggregate_adapter< Foo>
和 Foo
是相关的, foo
可转换为 std :: shared_ptr< Foo> $ c $
Since aggregate_adapter<Foo>
and Foo
are related, foo
is convertible to std::shared_ptr<Foo>
as well.
不幸的是,使用转发还使不可能像 std :: make_shared< aggregate_adapter< Foo>>>>({{h','e','l','l' ,'o'},5,'c');
而不显式指定类型,但是对make_shared已经应用了相同的限制。
Unfortunately, the use of forwarding also makes it impossible to brace-init any of the members like std::make_shared<aggregate_adapter<Foo>>({'h','e','l','l','o'}, 5, 'c');
without specifying the type explicitly, but the same restriction applies to make_shared already.
这篇关于在std :: make_shared中使用c ++聚合初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!