ron*_*nag 3 c++ comparison smart-pointers c++11
让我们说我想实现一个智能指针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();
}
Run Code Online (Sandbox Code Playgroud)
等等......对于其他运营商.
那么也许我想实现另一个智能指针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_;
};
Run Code Online (Sandbox Code Playgroud)
如果其中任何一个,除了比较两个之外a_ptr,都是真的,你的程序有一个bug.所以,放弃它.智能指针很聪明,因为它负责管理它背后的内存.而且你不能拥有两个不同的智能指针来管理一块内存.
考虑unique_ptr和shared_ptr.一旦拥有智能指针被销毁,就会破坏指针.第二,只有在所有拥有的智能指针被销毁时才会销毁指针.我认为很明显它会很快导致双重删除和其他有趣的东西.