具有 unique_ptr 个成员的对象的错误 C2280 向量
Error C2280 vector of objects that have unique_ptr members
我相信我知道为什么会发生这种情况,但是作为 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 studio17\community\vc\tools\msvc.12.25827\include\xmemory0 945
unique_ptr
不可复制,只能移动。这就是为什么它首先被称为独特的原因。
推送到 actors
时您使用了正确的方法,因此您只需要将其调整为 stages
。
app.stages.push_back(std::move(sta1));
我相信我知道为什么会发生这种情况,但是作为 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 studio17\community\vc\tools\msvc.12.25827\include\xmemory0 945
unique_ptr
不可复制,只能移动。这就是为什么它首先被称为独特的原因。
推送到 actors
时您使用了正确的方法,因此您只需要将其调整为 stages
。
app.stages.push_back(std::move(sta1));