在阅读《Beyond the C++ Standard Library: An Introduction to Boost》时,我得到了一个非常有趣的例子:
class A
{
public:
virtual void sing()=0;
protected:
virtual ~A() {};
};
class B : public A
{
public:
virtual void sing( )
{
std::cout << "Do re mi fa so la"<<std::endl;;
}
};
我做了一些测试:
int main()
{
//1
std::auto_ptr<A> a(new B); //will not compile ,error: ‘virtual A::~A()’ is protected
//2
A *pa = new B;
delete pa; //will not compile ,error: ‘virtual A::~A()’ is protected
delete (dynamic_cast<B*>(pa)); //ok
//3
boost::shared_ptr<A> a(new B);//ok
}
我很好奇的是 ~shared_ptr 是如何工作的? 它是如何推导出派生类B的?
提前感谢您的帮助!
谢谢大家, 我写了一个关于 ~shared_ptr 如何工作的简单示例
class sp_counted_base
{
public:
virtual ~sp_counted_base(){}
};
template<typename T>
class sp_counted_base_impl : public sp_counted_base
{
public:
sp_counted_base_impl(T *t):t_(t){}
~sp_counted_base_impl(){delete t_;}
private:
T *t_;
};
class shared_count
{
public:
static int count_;
template<typename T>
shared_count(T *t):
t_(new sp_counted_base_impl<T>(t))
{
count_ ++;
}
void release()
{
--count_;
if(0 == count_) delete t_;
}
~shared_count()
{
release();
}
private:
sp_counted_base *t_;
};
int shared_count::count_(0);
template<typename T>
class myautoptr
{
public:
template<typename Y>
myautoptr(Y* y):sc_(y),t_(y){}
~myautoptr(){ sc_.release();}
private:
shared_count sc_;
T *t_;
};
int main()
{
myautoptr<A> a(new B);
}
关键是:
- 模板构造函数
- ~shared_ptr中没有被删除的资源,被shared_count删除了
最佳答案
令人惊讶的是,这里的关键不是boost::shared_ptr
析构函数,但它的构造函数。
如果您查看 boost/shared_ptr.hpp
, 你会看到 shared_ptr<T>
没有“简单”的构造函数期望 T *
但是:
template<class Y>
explicit shared_ptr( Y * p );
在 //3
当你构建一个 boost::shared_ptr
来自 B *
, 未转换为 A *
发生,shared_ptr
内部是用实际的 B
构建的类型。销毁对象后,删除发生在 B
指针(不是通过基类指针)。
关于c++ - boost::~shared_ptr 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4560372/