12

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

I use gcc 4.6.1 to compile this code

int main()
{
    std::vector<std::unique_ptr<int>> vec({
            std::unique_ptr<int>(new int(0)),
            std::unique_ptr<int>(new int(1)),
        });
    return 0;
}

In what g++ complains there is something like

/usr/lib/gcc/x86_64-unknown-linux-gnu/4.6.1/../../../../include/c++/4.6.1/bits/stl_construct.h:76:7: **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<int>, std::unique_ptr<_Tp, _Dp> = std::unique_ptr<int>]'

It seems g++ still tries copy constructor in this case, though what I have put into initializer list are r-values. So how could I initialize a container of noncopyable with initializer list?

Community
  • 1
  • 1
neuront
  • 9,312
  • 5
  • 42
  • 71

1 Answers1

10

You can't move objects out of initializer lists, since they only allow const access to their members. As such, you can't use initializer lists and move constructors; they can only be copied.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 2
    As the next-best thing, though, you could use `reserve(2)` followed by two calls to `emplace`, which won't even invoke any move constructors. – Kerrek SB Jul 24 '11 at 11:24
  • Hmm, that should be a bug of C++0x. In this situation members of initializer list should have a r-value access. – neuront Jul 26 '11 at 04:06