Move Semantics with unique_ptr

后端 未结 2 818
轮回少年
轮回少年 2021-02-14 01:47

I am using Visual Studio 2012 Update 2 and am having trouble trying to understand why std::vector is trying to use the copy constructor of unique_ptr. I have looked at similar

2条回答
  •  無奈伤痛
    2021-02-14 02:38

    MyObject o; defines o to be an object. Which means it's a l-value. Doing s.push_back(o); then invokes the l-value overload of push_back() (it has no other choice), which tries to create a copy.

    Since your class is noncopyable, you have to move the object into the vector:

    for (int i = 0; i < 5; ++i)
    {
        MyObject o;
        s.push_back(std::move(o));
    }
    

提交回复
热议问题