How to initialize a container of noncopyable with

2019-02-16 14:33发布

问题:

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?

回答1:

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.