If I pass the following code through my GCC 4.7 snapshot, it tries to copy the unique_ptr
s into the vector.
#include <vector>
#include <memory>
int main() {
using move_only = std::unique_ptr<int>;
std::vector<move_only> v { move_only(), move_only(), move_only() };
}
Obviously that cannot work because std::unique_ptr
is not copyable:
error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete; std::unique_ptr<_Tp, _Dp> = std::unique_ptr]'
Is GCC correct in trying to copy the pointers from the initializer list?
Best Answer
Edit: Since @Johannes doesn't seem to want to post the best solution as an answer, I'll just do it.
The iterators returned by
std::make_move_iterator
will move the pointed-to element when being dereferenced.Original answer: We're gonna utilize a little helper type here:
Sadly, the straight-forward code here won't work:
Since the standard, for whatever reason, doesn't define a converting copy constructor like this:
The
initializer_list<rref_wrapper<move_only>>
created by the brace-init-list ({...}
) won't convert to theinitializer_list<move_only>
that thevector<move_only>
takes. So we need a two-step initialization here: