英文:
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<MyStruct>{.my_number = 4, .my_string = "two"};
// not like this
auto my_struct = std::make_unique<MyStruct>(4, "two");
I've managed to create a new object as an argument to unique_ptr
, but find it ugly:
auto my_struct = std::unique_ptr<MyStruct>(new MyStruct{.my_number = 4, .my_string = "two"});
答案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 = "two"}); // error: deduction failed
for fear of the argument being new MyStruct[…]
(which has the same type).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论