Initializer-list-constructing a vector of noncopyable (but movable) objects
Solution 1:
Maybe this clause from 8.5.4.5 explains it (my emphasis):
An object of type std::initializer_list is constructed from an initializer list as if the implementation allocated an array of N elements of type E, where N is the number of elements in the initializer list. Each element of that array is copy-initialized with the corresponding element of the initializer list, and the std::initializer_list object is constructed to refer to that array.
So you can only initialize from lists if the objects are copyable.
Update: As Johannes points out, copy-initialization can be realized by both copy and move constructors, so that alone isn't enough to answer the question. Here is, however, an excerpt of the specification of the initializer_list
class as described in 18.9:
template<class _E>
class initializer_list
{
public:
typedef _E value_type;
typedef const _E& reference;
typedef const _E& const_reference;
typedef size_t size_type;
typedef const _E* iterator;
typedef const _E* const_iterator;
Note how there are no non-constant typedefs!
I just tried making an IL constructor which would traverse the initializer list via std::make_move_iterator
, which failed because const T &
cannot be converted to T&&
.
So the answer is: You cannot move from the IL, because the standard says so.
Solution 2:
It appears it might be a compiler issue. This works in g++ 4.5.1 (click for IdeOne online demo)
Conclusion: It was, in the sense that older g++ implementations did not correctly flag an error; initializer lists do not support moving their elements (elements are implicitely copied in the process). Thank to Kerrek SB for quoting the helpful phrase from the standard.
Old proceedings (for the sake of understanding the comments:)
Edit Found out that at least g++ 4.6.1+ seem to have your complaint about this code.
Edit Upon reading the source to std::initializer_list<T>
I'm starting to get the impression that this is not supported by the library (it looks intentional). Whether the standard actually allows for an initializer list to forward the xvalue-ness of it's elements... I wouldn't be surprised if they stopped there (perfect forwarding is still not easily supported in C++0x I think, and not all initializer parameters would need to have the same (deductable) type.
Anyone with more standardese under his belt care to help out? http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2640.pdf
#include <vector>
struct S
{
S(int) {};
S(S&&) {};
};
int main()
{
std::vector<S> v = {S(1), S(2), S(3)};
std::vector<S> w = {std::move(S(1)), std::move(S(2)), std::move(S(3))};
std::vector<S> or_even_just = {1, 2, 3};
}