本文介绍了错误C2280:尝试引用已删除的函数(unique_ptr)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经历了一些使用原始指针的旧代码,并将其更改为 unique_ptr s。现在,当我尝试编译代码时,出现以下错误消息:

I went through some old code that used raw pointers and changed them to unique_ptrs instead. Now, when I try to compile the code, I get this error message:

有关此情况的编译器输出非常大-为了节省空间,请参见。

The compiler output about the situation is huge - to save space in this question, see it here.

据我所知,这与我使用唯一指针的方式有关。它从此处开始(level.h,第65-66行):

As far as I can tell, it has something to do with the way I use the unique pointers. It starts from here (level.h, lines 65-66):

typedef std::unique_ptr<Enemy> PEnemy;
std::list<PEnemy> m_enemies;

现在,我在编译器输出中获得的下一个线索是basesource.cpp中的第47行: / p>

Now, the next clue I get in the compiler output is the line 47 in basesource.cpp:

std::list<PEnemy> enemies = Game::LEVEL->getEnemies();

这为什么会引起问题?如何解决该错误?

Why does this cause problems? How can I fix the error?

推荐答案

unique_ptr s无法复制;只感动!但是由于 std :: list 应该能够在内部移动它们,所以唯一的问题应该是您要对列表本身执行分配。

unique_ptrs cannot be copied; only moved! But since std::list should be able to move them around internally, your only problem should be that assignment you're performing to the list itself.

可以移动列表吗?


  • std :: list< PEnemy>敌人= std :: move(Game :: LEVEL-> getEnemies());

  • std::list<PEnemy> enemies = std::move(Game::LEVEL->getEnemies());

  • const std :: list< PEnemy>&敌人= Game :: LEVEL-> getEnemies();

  • const std::list<PEnemy>& enemies = Game::LEVEL->getEnemies();

如果没有(这取决于在 Game :: LEVEL-> getEnemies()的返回类型上,您将需要使用上述哪种解决方案,如果有的话,进行深层复制,或者将深层复制切换到 shared_ptr

If not (and it will depend on the return type of Game::LEVEL->getEnemies() as to which, if either, of the above solutions you can use), you're going to need to do a deep, deep copy or switch to shared_ptr instead.

这全部可能似乎是一个障碍,但这实际上是通过严格执行有关指尖所有者所有权的规则来帮您一个忙。

This all may seem to be a hindrance, but it's actually doing you a favour by keeping the rules regarding ownership of your pointees strictly enforced.

这篇关于错误C2280:尝试引用已删除的函数(unique_ptr)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 12:14