1

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"});
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
uni
  • 539
  • 1
  • 9
  • 21
  • 6
    Nope, that's not possible, since `std::make_unique` is a function template. You could of course use the implicitly created move constructor here, but that doesn't seem much better than your last code snippet: `auto my_struct = std::make_unique(MyStruct{.my_number = 4, .my_string = "two"});` – fabian May 25 '23 at 13:59

1 Answers1

3

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

Davis Herring
  • 36,443
  • 4
  • 48
  • 76