0
std::unique_ptr<std::array<int, 3>> nums = std::make_unique<std::array<int, 3>, std::initializer_list<int>>({ 5, 6, 7 });

I read here that this is the way to do it, but the compiler throws the following error:
C2664: 'std::array::array(std::array &&)': cannot convert argument 1 from 'std::initializer_list' to 'const std::array &'

Does anyone have an idea why this is happening?

  • 1
    In the other example `Foo` has a constructor taking an `initializer_list` parameter. `std::array` does not have that. – Bo Persson Mar 06 '18 at 19:42
  • @BoPersson that sounds like an answer – Brian Bi Mar 06 '18 at 19:45
  • @BoPersson Ah I see, is there another way to quickly initialize a `unique_ptr`? – FirstProphet Mar 06 '18 at 19:45
  • 3
    what about `std::unique_ptr> nums = std::make_unique>(std::array{ 1, 2, 3 });` quick enough? – Killzone Kid Mar 06 '18 at 19:56
  • In common practice, STL containers with unique_ptr help to avoid costly operations, or when an object can't be copied, like std::thread. Is there any strict need to use point wrappers around STL containers? – Smit Ycyken Mar 06 '18 at 19:57
  • @SmitYcyken I want to return the array from a function. – FirstProphet Mar 06 '18 at 20:03
  • @KillzoneKid Doesn't this copy the array? – FirstProphet Mar 06 '18 at 20:04
  • @FirstProphet Looks to me like a case for compiler copy elision – Killzone Kid Mar 06 '18 at 20:08
  • If you want to modify the existing array why not to use `void do_smth(std::vector& result);`. It seems to be bad practice to return a vector from a function. – Smit Ycyken Mar 06 '18 at 20:09
  • @SmitYcyken I thought about that, but it's sort of annoying to have to manually create a new array everytime I want to call the function. I was hoping there is an easy way for a function to create and return an array... – FirstProphet Mar 06 '18 at 20:17
  • 1
    If you really want to return an array of 3 int's, it will be much faster to pass it by value instead of allocating it on the heap. Then it might even get optimized away with 0 memory access. – rustyx Mar 06 '18 at 20:25
  • @rustyx It's more about the general concept of things, imagine it were an array of 1 billion ints or whatever ... – FirstProphet Mar 07 '18 at 00:39
  • @FirstProphet, how about using iterators? Instead of a returning a collection you take an output iterator as argument. It's more flexible too. –  Mar 07 '18 at 07:38

0 Answers0