假设我想实现一个智能指针a_ptr
,它可以与其他智能指针进行比较。
然后我需要实现比较运算符的所有排列:
template<class T, class U>
bool operator==(const a_ptr<T>& a, const a_ptr<U>& b)
{
return a.get() == b.get();
}
template<class T, class U>
bool operator==(const std::shared_ptr<T>& a, const a_ptr<U>& b)
{
return a.get() == b.get();
}
template<class T, class U>
bool operator==(const a_ptr<T>& a, const std::shared_ptr<U>& b)
{
return a.get() == b.get();
}
等等...对于其余的运算符(operator)。
那么也许我想实现另一个智能指针 b_ptr
,它会为每个比较运算符提供 6 个版本(因为我希望它也能与 a_ptr
一起使用) ,显然无法管理。
有什么办法可以解决这个问题吗?
编辑:
我可能应该提到我想围绕智能指针创建包装器,在这种情况下这个问题更有意义,例如
template<typename T>
class a_ptr
{
public:
const T* get() const {return p_.get();}
private:
std::shared_ptr<T> p_;
};
template<typename T>
class b_ptr
{
public:
const T* get() const {return p_.get();}
private:
a_ptr<T> p_;
};
最佳答案
如果除了比较两个 a_ptr
之外,其中任何一个成立,则您的程序有错误。所以,干脆放弃吧。智能指针之所以智能,是因为它负责管理它背后的内存。而且您不能让 两个 不同的智能指针管理一 block 内存。
考虑 unique_ptr
和 shared_ptr
。一旦拥有的智能指针被销毁,一个指针就会被销毁。 Second 仅当所有 拥有的智能指针被销毁时才销毁指针。我认为这很明显会很快导致双重删除和其他有趣的事情。
关于c++ - 自定义智能指针和多项式比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8703955/