【问题标题】:Error: C2280 Creating a vector of unique_ptr to Class错误:C2280 创建一个 unique_ptr 的向量到 Class
【发布时间】:2016-07-26 02:19:09
【问题描述】:

似乎在 vector<unique_ptr<UserInterface>> 中使用 unique_ptr 时出现错误说明:

Error 1 error C2280: 'std::unique_ptr<UserInterface,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function c:\pr...ude\xmemory0 593 1 Win32Project1

看起来,没有配置允许我存储指向 UserInterface 类的 [智能] 指针,该类具有简单的结构:

#define InterfaceContruct vector<unique_ptr<UserInterface>>

class UserInterfaceMgmt
{
public:
    UserInterfaceMgmt();
    ~UserInterfaceMgmt();

    InterfaceContruct Interface;

    void AddUIElement();
    void RemoveUIElement();
    void DrawInterface();
    void MoveElement();
private:
};

即使没有调用任何函数,也会出现错误(InterfaceContruct Interface; 已实例化)我尝试将复制构造函数放入 private,但它仍然存在。

.cpp 文件是:

#include "stdafx.h"
#include "UserInterfaceMgmt.h"

UserInterfaceMgmt::UserInterfaceMgmt()
{
}

UserInterfaceMgmt::~UserInterfaceMgmt()
{
}

void UserInterfaceMgmt::DrawInterface(){
    for (UINT i = 0; i < Interface.size(); i++)
    {
        Interface[i]->Draw();
    }
}

【问题讨论】:

  • 该错误消息的实例化回溯是什么?
  • 你的“UserInterface”类是什么样子的?

标签: pointers c++11 vector game-engine copy-constructor


【解决方案1】:

std::vector(以及std:: 中的大多数其他容器)要求值类型是可复制构造的。 std::unique_ptr 不可复制构造。使用std::shared_ptr 或任何其他可复制构造的类型/指针。

线索是寻找attempting to reference a deleted function。这意味着= delete 已经使用了一些方法。例如:

struct Foo
{
    Foo(const Foo & rhs) = delete; // A deleted function
}

【讨论】:

  • 我明白了。这样可行; '如此执着于让它发挥作用,我“知道”我可以飞。我知道 unique_ptr 会删除复制构造函数,但试图巧妙地解决它。
  • 我要测试一个基本配置,然后回来标记为答案。
  • @RashidEllis:你不应该使用#define InterfaceContruct vector&lt;unique_ptr&lt;UserInterface&gt;&gt;,而应该使用typedef vector&lt;unique_ptr&lt;UserInterface&gt;&gt; InterfaceContruct或新的C++11方式using InterfaceContruct = vector&lt;unique_ptr&lt;UserInterface&gt;&gt;
  • for using InterfaceContruct = vector&lt;shared_ptr&lt;UserInterface&gt;&gt;; 编译器处理这些的方式有什么不同吗?
  • 有效!再次感谢(我查看了处理器定义,看起来 #define 是一个盲定义;它已切换到 using... C++11 类型)
猜你喜欢
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-24
  • 2014-07-21
  • 2016-08-18
  • 2013-02-18
相关资源
最近更新 更多