gpt4 book ai didi

c++ - boost::~shared_ptr 是如何工作的?

转载 作者:IT老高 更新时间:2023-10-28 22:59:51 26 4
gpt4 key购买 nike

在阅读《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);
}

关键是:

  1. 模板构造函数
  2. ~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/

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