我正在为boost::filtered_graph创建自己的自定义过滤器类。WeightMap概念必须具有默认构造函数、复制构造函数和赋值运算符。
我创建了下面的类,它有一个std::shared_ptr私有成员。我的问题是如何编写赋值运算符。复制构造函数不是问题,但赋值运算符无法正常工作。
class BFDMFilter
{
private:
const BGraph* m_battlemap;
const std::shared_ptr<MoveAbility> m_mv_ab;
public:
BFDMFilter() : m_battlemap(nullptr), m_mv_ab() { }
BFDMFilter(const BGraph* bmap, std::shared_ptr<MoveAbility> mv) : m_battlemap(bmap), m_mv_ab(mv) { }
BFDMFilter(const BFDMFilter& filter) : m_battlemap(filter.m_battlemap), m_mv_ab(filter.m_mv_ab) { }
BFDMFilter& operator=(const BFDMFilter& filter)
{
if(this != &filter)
{
m_battlemap = filter.m_battlemap;
m_mv_ab = filter.m_mv_ab;
}
return *this;
}
bool operator()(const Edge& edge) const
{
Tile::TileEdge path = (*m_battlemap)[edge];
return m_mv_ab->CanMove(path.TerrainType()) > 0.0;
}
bool operator()(const Vertex& vertex) const
{
Tile tile = (*m_battlemap)[vertex];
return m_mv_ab->CanMove(tile.TerrainType()) > 0.0;
}
};
然后就出现了编译错误:
error: passing ‘const std::shared_ptr<momme::battle::MoveAbility>’ as ‘this’ argument of ‘std::shared_ptr<_Tp>& std::shared_ptr<_Tp>::operator=(std::shared_ptr<_Tp>&&) [with _Tp = momme::battle::MoveAbility, std::shared_ptr<_Tp> = std::shared_ptr<momme::battle::MoveAbility>]’ discards qualifiers [-fpermissive]
我明白了,赋值运算符在执行赋值时会修改shared_ptr的引用计数,以便跟踪有多少个打开的引用。但问题是,我该如何编写赋值运算符呢?std :: weak_ptr也具有相同的行为,如果我将引用设为非const,则boost库会报错函数已被删除。
std::shared_ptr<const MoveAbility> m_mv_ab
吗?你想让std::shared_ptr
本身是const还是它所指向的对象是const? - Stephen Linconst
数据成员进行赋值。这不仅适用于shared_ptr
。 - juanchopanza