I am attempting to make a Deck
class that holds a vector of unique_ptr<Card>
, but attempting to sort the vector results in this error:
Error 1 error C2280: 'std::unique_ptr>:: unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
Looking through Stack Overflow, it looks like there is a bug in VS 2013 where vectors incorrectly tries to copy unique_ptr
s instead of moving them, so I attempted to add my own move function to my Deck
class, but I still get the error.
Here is a minimal example of the code in question (Card
is just a dummy class, with no objects in it):
Deck.h:
#include "Card.h"
#include <vector>
#include <memory>
class Deck
{
public:
typedef std::unique_ptr<Card> cardPtr;
Deck();
Deck(Deck && other)
: mDeck(std::move(other.mDeck))
{
}
Deck& operator=(Deck other)
{
swap(*this, other);
return *this;
}
friend void swap(Deck& lhs, Deck& rhs);
void sortDeck();
private:
static bool compareCards(cardPtr A, cardPtr B);
private:
std::vector<cardPtr> mDeck;
};
Deck.cpp:
#include "Deck.h"
#include <algorithm>
Deck::Deck()
{
}
void swap(Deck& lhs, Deck& rhs)
{
using std::swap;
swap(lhs.mDeck, rhs.mDeck);
}
bool Deck::compareCards(cardPtr A, cardPtr B)
{
return true; //dummy- normally would have logic here
}
void Deck::sortDeck()
{
std::sort(mDeck.begin(), mDeck.end(), compareCards); //bug happens here
}
Any ideas about how to fix this? I'm sure I must be missing something fairly obvious, but I have been beating my head against this and googling it for a fair amount of time now, and could use some help.
Your compareCards
function takes the unique_ptr
s by value, this won't work as they are not copyable (the unique_ptr
copy constructor is implicitly deleted due to the presence of move constructors, a copyable unique_ptr
wouldn't be very unique would it?).
Change it to
bool compareCards(cardPtr const& A, cardPtr const& B);