如何使用初始化列表初始化不可复制的容器?

可能重复:
我可以列出初始化一个只移动类型的向量吗?

我使用 gcc 4.6.1 编译这段代码

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

在 g++ 的抱怨中,有类似的东西

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>]'

在这种情况下,g++ 似乎仍在尝试复制构造函数,尽管我放入初始化列表的是 r 值.那么如何使用初始化列表初始化一个不可复制的容器呢?

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?

推荐答案

您不能将对象移出初始化列表,因为它们只允许对其成员进行 const 访问.因此,您不能使用初始化列表和移动构造函数;它们只能被复制.

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.

相关文章