【问题标题】:Error C2280 vector of objects that have unique_ptr members具有 unique_ptr 成员的对象的错误 C2280 向量
【发布时间】:2020-02-18 14:53:14
【问题描述】:

我相信我知道为什么会发生这种情况,但是作为 c++ 新手,我不确定处理它的 正确 方法是什么(不使用原始指针)。根据我的研究,正在发生的事情是,当我尝试将push_backStage 对象复制到向量中时,正在尝试复制,并且由于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 

【问题讨论】:

  • app.stages.push_back(std::move(sta1)); ? Stage 的复制构造函数被隐式删除,但移动构造函数应该可用。
  • 使用shared_ptr

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多