c++ - 在 VS 2013 中对 unique_ptr 的 vector 进行排序

标签 c++ vector visual-studio-2013 unique-ptr playing-cards

我正在尝试制作 Deck包含 unique_ptr<Card> vector 的类,但尝试对 vector 进行排序会导致此错误:

Error 1 error C2280: 'std::unique_ptr>:: unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function

查看 Stack Overflow,VS 2013 中似乎存在一个错误,其中 vector 错误地尝试复制 unique_ptr s 而不是移动它们,所以我尝试将自己的移动功能添加到我的 Deck类,但我仍然收到错误。

这是相关代码的一个最小示例(Card 只是一个虚拟类,其中没有任何对象):

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;
};

甲板.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
}

关于如何解决这个问题有什么想法吗?我确定我一定遗漏了一些相当明显的东西,但我一直在努力反对这一点,并在谷歌上搜索了相当长的时间,现在需要一些帮助。

最佳答案

您的 compareCards 函数按值获取 unique_ptr,这将不起作用,因为它们不可复制(unique_ptr 复制构造函数是由于移动构造函数的存在而被隐式删除,可复制的 unique_ptr 不会非常独特,对吗?)。

改成

bool compareCards(cardPtr const& A, cardPtr const& B);

关于c++ - 在 VS 2013 中对 unique_ptr 的 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25716272/

相关文章:

c++ - 三十部分库中的线程安全

c++ - C++ 中用于将 wchar_t* 或 char* 分配给数组的模板方法

c++ - 如何使boost线程自毁? (C++)

c++ - 如何在 C++ 中填充数据或访问 3 维 vector

c# - 在构造函数中调用异步方法?

c++ - 令人困惑的 (*this) 指针转换

c++ - 将 1 加到由数字数组表示的数字

c++ - 重载 << 运算符 : struct with vector of structs

visual-studio-2013 - OpsHub VS Migration 请求管理员权限,我是 Visual Studio 管理员

mysql - C++ 如何执行2个及更多查询命令?