具有unique_ptr成员的对象的C2280错误向量

问题描述 投票:-1回答:1

我相信我知道为什么这正在发生,但是对于C ++来说,我不确定正确处理它的方式是什么(无需使用原始指针)。根据我的研究,正在发生的事情是,当我尝试将push_back对象Stage转换为向量时,正在尝试复制,并且由于Stage包含已删除副本构造函数的unique_ptr成员,因此会遇到以下错误。

我的理解正确吗?如果是这样,那么在现代c ++中解决此问题的最佳方法是什么?

最小可复制示例

#include <iostream>
#include <vector>
#include <memory>

class Actor
{
private:
    int prop1 = 1;
    int prop2 = 2;
public:
    Actor() {}
};

class Stage
{
public:
    Stage() {}
    std::vector<std::unique_ptr<Actor>> actors;
};

class App
{
public:
    App() {}
    std::vector<Stage> stages;
};

int main()
{
    auto act1 = std::make_unique<Actor>();

    auto sta1 = Stage();
    sta1.actors.push_back(std::move(act1));

    auto app = App();
    app.stages.push_back(sta1); // Issue occurs when copying Stage object into vector since Stage object contains members of type unique_ptr (or at least that's my best guess from the research I have done)

    std::cin.get();
    return 0;
}

来自MSVC的编译器错误

Error   C2280   'std::unique_ptr<Actor,std::default_delete<_Ty>>::unique_ptr(
const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to 
reference a deleted function    SmartPointers   
c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.12.25827\include\xmemory0    945 
c++ vector smart-pointers unique-ptr
1个回答
0
投票

unique_ptr无法复制,只能移动。这就是为什么它首先被称为唯一的原因。

推到actors时使用了正确的方法,因此只需要使其适应stages

 app.stages.push_back(std::move(sta1));
© www.soinside.com 2019 - 2024. All rights reserved.