【发布时间】:2020-02-18 14:53:14
【问题描述】:
我相信我知道为什么会发生这种情况,但是作为 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
【问题讨论】:
-
app.stages.push_back(std::move(sta1));?Stage的复制构造函数被隐式删除,但移动构造函数应该可用。 -
使用
shared_ptr。
标签: c++ vector smart-pointers unique-ptr