JordanW JordanW - 1 year ago 133
C++ Question

Sorting a vector of unique_ptr in VS 2013

I am attempting to make a

class that holds a vector of
, 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
s instead of moving them, so I attempted to add my own move function to my
class, but I still get the error.

Here is a minimal example of the code in question (
is just a dummy class, with no objects in it):


#include "Card.h"
#include <vector>
#include <memory>

class Deck
typedef std::unique_ptr<Card> cardPtr;


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();

static bool compareCards(cardPtr A, cardPtr B);

std::vector<cardPtr> mDeck;


#include "Deck.h"
#include <algorithm>


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.

Answer Source

Your compareCards function takes the unique_ptrs 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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download