10
votes

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:

Error 1 error C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function d:\visual studio 2013\vc\include\xmemory0

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

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;

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?

1
The error is reminding you that std::unique_ptr is not copyable.juanchopanza

1 Answers

19
votes

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.

Can you move the list?

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

Or use a reference to it instead?

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

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.