c++ - 具有unique_ptr成员的对象的错误C2280 vector

标签 c++ vector smart-pointers unique-ptr

我相信我知道为什么会这样,但是对于c++来说,我是不确定的(不使用原始指针)处理的正确方法是什么。根据我的研究,正在发生的事情是,当我尝试将push_back对象Stage转换为 vector 时,正在尝试复制,并且由于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 

最佳答案

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

在推送到actors时,您使用了正确的方法,因此您只需将其调整为stages即可。

 app.stages.push_back(std::move(sta1));

关于c++ - 具有unique_ptr成员的对象的错误C2280 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60283630/

相关文章:

c++ - 如何使用 operator+ 重载函数正确返回对象?

c++ - 在两个不同的程序之间发送/接收数据

c++ - vector 数组还是数组 vector ?

wpf - 将 EPS 转换为 Xaml

c++ - 如何在最后一个客户端完成时删除持久对象的实例

c++ - 当我们有设置值的 setter 时,为什么我们要使用参数化构造函数

c++ - 如何只选择需要的 Qt 头文件?

vector - rust 是否可以为不同的数据结构提供统一的 Iterator 接口(interface)?

c++ - 智能指针+循环+ "->"

c++ - 如何判断哪个类拥有指针