如何初始化非初始化列表的非可复制容器? [英] How to initialize a container of noncopyable with initializer list?

查看:321
本文介绍了如何初始化非初始化列表的非可复制容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我可以列表初始化一个只移动类型的向量吗?

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

我使用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.

这篇关于如何初始化非初始化列表的非可复制容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆