uni
uni

Reputation: 611

std::make_unique and designated initializers

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"});

Upvotes: 1

Views: 549

Answers (2)

Pax
Pax

Reputation: 132

It is not a perfect answer but you can use std::make_unique like this:

auto my_struct = std::make_unique<MyStruct>(std::move(
    MyStruct{.my_number = 4, .my_string = "two"}));

Upvotes: -1

Davis Herring
Davis Herring

Reputation: 39818

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

Upvotes: 3

Related Questions