27

One can push_back rvalues of a noncopyable-but-movable type into a vector of that type:

#include <vector>

struct S
{
    S(int);
    S(S&&);
};

int main()
{
    std::vector<S> v;
    v.push_back(S(1));
    v.push_back(S(2));
    v.push_back(S(3));
}

However, when I try to initializer-list-construct the vector with the same rvalues, I get errors about a copy constructor being required:

#include <vector>

struct S
{
    S(int);
    S(S&&);
};

int main()
{
    std::vector<S> v = {S(1), S(2), S(3)};
}

I get the following errors with GCC 4.7:

In file included from include/c++/4.7.0/vector:63:0,
                 from test.cpp:1:
include/c++/4.7.0/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = S, _Args = {const S&}]':
include/c++/4.7.0/bits/stl_uninitialized.h:77:3:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const S*, _ForwardIterator = S*, bool _TrivialValueTypes = false]'
include/c++/4.7.0/bits/stl_uninitialized.h:119:41:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const S*, _ForwardIterator = S*]'
include/c++/4.7.0/bits/stl_uninitialized.h:260:63:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = const S*, _ForwardIterator = S*, _Tp = S]'
include/c++/4.7.0/bits/stl_vector.h:1185:4:   required from 'void std::vector<_Tp, _Alloc>::_M_range_initialize(_ForwardIterator, _ForwardIterator, std::forward_iterator_tag) [with _ForwardIterator = const S*, _Tp = S, _Alloc = std::allocator<S>]'
include/c++/4.7.0/bits/stl_vector.h:362:2:   required from 'std::vector<_Tp, _Alloc>::vector(std::initializer_list<_Tp>, const allocator_type&) [with _Tp = S, _Alloc = std::allocator<S>, std::vector<_Tp, _Alloc>::allocator_type = std::allocator<S>]'
test.cpp:11:41:   required from here
include/c++/4.7.0/bits/stl_construct.h:77:7: error: no matching function for call to 'S::S(const S&)'
include/c++/4.7.0/bits/stl_construct.h:77:7: note: candidates are:
test.cpp:6:5: note: S::S(S&&)
test.cpp:6:5: note:   no known conversion for argument 1 from 'const S' to 'S&&'
test.cpp:5:5: note: S::S(int)
test.cpp:5:5: note:   no known conversion for argument 1 from 'const S' to 'int'

Should this be allowed? I see no technical obstacles to it being allowed, but I don't have the Standard handy at the moment...

HighCommander4
  • 50,428
  • 24
  • 122
  • 194
  • It looks like the only way to fill a vector with moveable objects is to revert to the old style: std::vector v; v.emplace_back(S(1)); v.emplace_back(S(2)); v.emplace_back(S(3));` (or shorter/obcure `v.emplace_back(1); etc ...`). Sad, isn't it? – alfC Jan 25 '14 at 04:01
  • You can use push_back if the template type is MoveInsertable. – Jens Åkerblom Oct 25 '14 at 14:54
  • @JensÅkerblom: I'm aware; in fact, that's what my first code snippet shows. Sometimes, though, you want to use an inline syntax. – HighCommander4 Oct 25 '14 at 21:48
  • Similar question: http://stackoverflow.com/questions/8468774/can-i-list-initialize-a-vector-of-move-only-type – M.M Nov 10 '15 at 00:51

4 Answers4

16

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • @sehe: it's a quote from the N3290 FDIS. I assume it's normative! :-) – Kerrek SB Aug 29 '11 at 17:21
  • I see. This seems to be a missed optimization opportunity in the standard, then... perhaps it will be fixed in the next version :) – HighCommander4 Sep 02 '11 at 19:31
  • 2
    This answer confuses more than it helps. Copy-initializing does not mean to "only copy but not move". Copy-initializing may well involved moving. It just means that you initialize as-if you had done `T t = e;`. `e` can be some rvalue moved into `t`. – Johannes Schaub - litb Sep 03 '11 at 12:49
  • @Johannes: I never said otherwise - I didn't say which sort of construction is invoked consequent to the copy-initialization. Do you have a suggestion for improvement? – Kerrek SB Sep 03 '11 at 13:24
  • @Johannes: So why does the moving not work, then? Is it just the libstdc++ implementation, or is there something else in the standard that forbids it? – HighCommander4 Sep 05 '11 at 09:09
  • I updated the answer to contain the real reason you cannot move! – Kerrek SB Sep 05 '11 at 11:02
9

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};
}

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • This does not help at all (I get the same errors), and that's not surprising - all std::move does is turn an lvalue into an rvalue. Since S(1), S(2), and S(3) are already rvalues, wrapping them in std::move accomplishes absolutely nothing. – HighCommander4 Aug 29 '11 at 14:34
  • @HighCommander4: no, std::move turns them into `rvalue references`. Not the same thing. Let me check things locally. **Meanwhile**, head over [here](http://stackoverflow.com/questions/5529881/move-semantics-stdmove-how-use-it/5529970#5529970) for some helpful hints/explanations – sehe Aug 29 '11 at 14:41
  • Pretty sure this is a compiler issue: https://ideone.com/bYhq9 shows it works just fine with g++ 4.5.1, with or without `std::move`. I suggest **using implicit construction** b.t.w. – sehe Aug 29 '11 at 14:50
  • 4
    That would be because GCC 4.5 doesn't implement the automatic generation of move/copy constructors correctly - it (incorrectly) generates a copy constructor for S even though a user-defined move constructor is present, and then uses it to copy the initializer-list objects. Add a private copy constructor to S, and you will see GCC 4.5 gives the same error now. – HighCommander4 Aug 29 '11 at 14:57
  • Have edited answer with findings. Thanks everyone for correcting; I've learned a thing or two about the compiler I'm using everyday – sehe Aug 29 '11 at 15:29
9

The initializer_list only provides const references and const iterators. There is no way for the vector to move from that.

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;
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
5

It seems the answer is No per Kerrek SB's answer. But you can achieve something similar by small helper functions using variadic templates:

#include <vector>
#include <utility>

template <typename T>
void add_to_vector(std::vector<T>* vec) {}

template <typename T, typename... Args>
void add_to_vector(std::vector<T>* vec, T&& car, Args&&... cdr) {
  vec->push_back(std::forward<T>(car));
  add_to_vector(vec, std::forward<Args>(cdr)...);
}

template <typename T, typename... Args>
std::vector<T> make_vector(Args&&... args) {
  std::vector<T> result;
  add_to_vector(&result, std::forward<Args>(args)...);
  return result;
}

struct S {
  S(int) {}
  S(S&&) {}
};

int main() {
  std::vector<S> v = make_vector<S>(S(1), S(2), S(3));
  return 0;
}
Community
  • 1
  • 1
Hiroshi Ichikawa
  • 616
  • 9
  • 10