std::make_unique和指定的初始化器

huangapple go评论69阅读模式
英文:

std::make_unique and designated initializers

问题

以下是翻译好的内容:

考虑这个结构:

struct MyStruct
{
  int my_number;
  std::string my_string;
};

是否可以使用指定初始化器创建一个std::unique_ptr?像这样:

// 像这样
auto my_struct = std::make_unique<MyStruct>{.my_number = 4, .my_string = "two"};
// 而不是这样
auto my_struct = std::make_unique<MyStruct>(4, "two");

我成功创建了一个新对象作为unique_ptr的参数,但觉得它不太美观:

auto my_struct = std::unique_ptr<MyStruct>(new MyStruct{.my_number = 4, .my_string = "two"});
英文:

Consider this structure:

struct MyStruct
{
  int my_number;
  std::string my_string;
};

Is it possible to create a std::unique_ptr using Designated initializers? Like this:

// like this
auto my_struct = std::make_unique&lt;MyStruct&gt;{.my_number = 4, .my_string = &quot;two&quot;};
// not like this
auto my_struct = std::make_unique&lt;MyStruct&gt;(4, &quot;two&quot;);

I've managed to create a new object as an argument to unique_ptr, but find it ugly:

auto my_struct = std::unique_ptr&lt;MyStruct&gt;(new MyStruct{.my_number = 4, .my_string = &quot;two&quot;});

答案1

得分: 3

> 使用指定初始化器创建`std::unique_ptr`是否可能?

**否**。不幸的是,您甚至不能使用CTAD来避免冗余:

auto my_struct = std::unique_ptr(new MyStruct{.my_number = 4, .my_string = "two"}); // 错误:推导失败

因为害怕参数是`new MyStruct[…​]`(它具有相同的类型)。
英文:

> Is it possible to create a std::unique_ptr using Designated initializers?

No. Unfortunately, you can’t even use CTAD to avoid the redundancy:

auto my_struct = std::unique_ptr(new MyStruct{.my_number = 4, .my_string = &quot;two&quot;});  // error: deduction failed

for fear of the argument being new MyStruct[…] (which has the same type).

huangapple
  • 本文由 发表于 2023年5月25日 21:49:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定