使用enable_shared_from_this
来源:互联网 发布:数据挖掘 毕业论文 编辑:程序博客网 时间:2024/04/24 17:35
说明
The header <boost/enable_shared_from_this.hpp> defines the class template enable_shared_from_this. It is used as a base class that allows a shared_ptr to the current object to be obtained from within a member function.
继承该类就可以进行基于当前子类进行安全的weap_ptr到shared_ptr的转换...
代码实例
以下代码中Y类继承enable_shared_from_this,, 从而我们可以直接在函数中调用shared_from_this获得该对象的shared_ptr
class Y:public enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
int main()
{
shared_ptr<Y> p(new Y);
// 调用f获得shared_ptr
shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q|| q< p));// p and q must share ownership
}
该类的实现
template<class T>class enable_shared_from_this
{
protected:
enable_shared_from_this()
{
}
enable_shared_from_this(enable_shared_from_this const&)
{
}
enable_shared_from_this & operator=(enable_shared_from_thisconst&)
{
return *this;
}
~enable_shared_from_this()
{
}
public:
shared_ptr<T> shared_from_this()
{
shared_ptr<T> p(_internal_weak_this);
BOOST_ASSERT(p.get() == this);
return p;
}
shared_ptr<T const> shared_from_this()const
{
shared_ptr<T const> p(_internal_weak_this);
BOOST_ASSERT(p.get() == this);
return p;
}
// Note: No, you don't need to initialize _internal_weak_this
//
// Please read the documentation, not the code
//
// http://www.boost.org/libs/smart_ptr/enable_shared_from_this.html
typedef T _internal_element_type; // for bcc 5.5.1
mutable weak_ptr<_internal_element_type> _internal_weak_this;
};
结论
这个实用类提供了简单的shared_ptr转换和安全的weak式验证... 这样通过继承就可以使用
shared_from_this进行安全当前类weak_ptr到shared_ptr的转换...
- 使用enable_shared_from_this
- 使用enable_shared_from_this
- 使用enable_shared_from_this
- enable_shared_from_this使用
- 使用enable_shared_from_this
- 使用enable_shared_from_this
- 使用enable_shared_from_this
- 使用enable_shared_from_this
- enable_shared_from_this
- enable_shared_from_this
- enable_shared_from_this
- enable_shared_from_this
- weak_ptr,enable_shared_from_this 的使用举例
- enable_shared_from_this 的使用及原理
- enable_shared_from_this模板类使用完全解析
- enable_shared_from_this模板类使用完全解析
- enable_shared_from_this模板类使用完全解析
- enable_shared_from_this模板类使用完全解析
- android -- 编译不同库及编译脚本之区别
- 黑马程序员——Java基础---面向对象(接口)--第7天--第95-97集
- 黑马程序员java自学总结之--模式
- freemarker.core.ParseException:Unexpected end of file reached
- 在vs&qt中使用资源文件
- 使用enable_shared_from_this
- 安卓渗透神器dsploit笔记
- QString字符转换
- 10W个为什么
- freemarker.core.InvalidReferenceException
- 黑马程序员——Java基础---面向对象(多态)--第8天--第98-106集
- 在做项目中遇到adapter中按钮换背影图失败
- 选择排序
- 如何去观察应用使用了多少内存