std::make_unique and designated initializers

250 Views Asked by At

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

There are 1 best solutions below

0
Davis Herring On

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).