c++ - 自定义智能指针和多项式比较运算符

标签 c++ comparison c++11 smart-pointers

假设我想实现一个智能指针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_ptrshared_ptr。一旦拥有的智能指针被销毁,一个指针就会被销毁。 Second 仅当所有 拥有的智能指针被销毁时才销毁指针。我认为这很明显会很快导致双重删除和其他有趣的事情。

关于c++ - 自定义智能指针和多项式比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8703955/

相关文章:

c# - 在 C# 中比较字符串和整数

c++ - 如果立即调用,为什么要将调用包含在 lambda 中?

c++ - 用 C++ 解释 boost::filesystem 的可移植通用路径格式

c++ - 防止通过接口(interface)删除对象

c++ - 你如何将一个类的函数作为参数传递给同一个类的另一个函数

c++ - 为什么我的 CUDA 应用程序没有启动?

r - 如何检查 df2 中的对是否与 R 中的 df1 (包括)成对?

java - 否定比较链

c++ - 为什么这里 `boost::bind()`不能换成 `std::bind()`呢?

c++11 - get `sizeof` 嵌套在类模板中的结构的非静态成员是否非法?