【发布时间】:2011-11-22 15:58:56
【问题描述】:
我的想法是我想要一个由std::shared_ptr 包装的类,仍然可以使用
就像它们不是指针一样,例如在我的班级中定义的 operator=
我的课被std::shared_ptr包裹后仍然可以使用。
例如
template <class Ty> class shared_ptr_proxy : public std::shared_ptr<Ty> {
public:
template<class Other> shared_ptr_proxy& operator=(const Other& rhs)
{
(*this->get()) = rhs;
return *this;
}
template<class Other> explicit shared_ptr_proxy(Other * ptr)
: std::shared_ptr<Ty>(ptr){};
};
// usage :
shared_ptr_proxy<float> obj = shared_ptr_proxy<float>(new float);
obj = 3.14;
它的工作,但有没有一种方法我不需要创建shared_ptr_proxy 或
从std::shared_ptr继承一个类?
和
如果我这样做了,有什么需要注意的地方吗?
【问题讨论】:
-
有什么理由不能只取消引用指针吗?
*ptrA = *ptrB;? -
因为这个想法是为了隐藏它实际上是一个指针
-
知道它实际上是一个指针通常是共享可变数据的一个特性。否则,不同对象可能对同一事物产生别名并不明显,因此
a = b可以更改c的值。毫无疑问,在某些情况下你确实想隐藏它是一个指针,对我来说最明显的是它实际上并没有共享(尽管使用了shared_ptr),它是一个 pImpl。
标签: c++ inheritance stl overloading shared-ptr