gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:40:51 26 4
gpt4 key购买 nike

假设我想实现一个智能指针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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com