1

Possible Duplicate:
Can I list-initialize a vector of move-only type?

I've tried this, but get complaints about calling ::std::unique_ptr's copy constructor. That doesn't seem right. :-(

#include <vector>
#include <memory>

int main()
{
   typedef ::std::unique_ptr<int> qint_ptr_t;
   ::std::vector<qint_ptr_t>{ {new int(5), new int(6) } };
   return 0;
}

Is there any way to initialize a vector of unique_ptr objects with an initialization list?

Community
  • 1
  • 1
Omnifarious
  • 54,333
  • 19
  • 131
  • 194
  • 3
    I don't think you can. Elements always need to be *copyable* from initializer lists. – Kerrek SB Oct 31 '12 at 00:34
  • 2
    Even if you can manage to get this to work, it won't be exception safe. – Benjamin Lindley Oct 31 '12 at 00:34
  • @BenjaminLindley: even if you replaced each brace item with `make_unique()` it wouldn't work. – Kerrek SB Oct 31 '12 at 00:36
  • I voted to close because it is an exact duplicate of that question. I'm sad. I was trying to create something that would initialize a new container by mapping the contents of an old container through the `transform` function. I wrapped `transform` up in a nice template class that inherited from `::std::initializer_list`. But the first thing I tried it on was a vector of `unique_ptr`'s because I was using the transform to do a deep copy of them. :-( – Omnifarious Oct 31 '12 at 00:41
  • 1
    Well, not all is lost, as you can see from my answer to that question. :) Just make it a two-step process without `initializer_list`. – Xeo Oct 31 '12 at 00:43
  • @Xeo: Unfortunately the real problem I'm trying to solve involves `::std::array`, so that solution won't work as `::std::array` can only do aggregate initialization. – Omnifarious Oct 31 '12 at 17:12
  • Uhm, for `std::array`, aggregate initialization should work. In my answer, I use a normal C-style array, but `std::array, 3> a = {make_unique(1), make_unique(2), make_unique(3)};` should work fine. – Xeo Oct 31 '12 at 17:17
  • @Xeo: _laugh_ Interesting. I'll try it. But it still doesn't solve my problem, which is more complex. I'm trying to make a generic aggregate mapping initializer that initializes an aggregate by running all the values from a container through a mapping function. The mapping function in this case maps from a `const unique_ptr &` to a `unique_ptr`. Perhaps I will put the more complex thing in a question and ask that. – Omnifarious Oct 31 '12 at 17:34

0 Answers0