How to initialize a container of noncopyable with initializer list? [duplicate]

↘锁芯ラ 提交于 2019-12-30 08:06:18

问题


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.



来源:https://stackoverflow.com/questions/6804216/how-to-initialize-a-container-of-noncopyable-with-initializer-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!