enable_share_from_this功能介绍
来源:互联网 发布:网络中了500万怎么领奖 编辑:程序博客网 时间:2024/04/24 18:23
http://www.2cto.com/kf/201212/175430.html
这个类很有意思,让一个被shared_ptr管理生命周期的类能够在自己的成员函数内部访问shared_ptr。有点绕。
举个例子,下面的代码在函数f内部通过this构造了shared_ptr对象,然后打印x_的值。
[cpp]
class B {
public:
B(): x_(4) {
cout << "B::B()" << endl;
}
~B() {
cout << "B::~B()" << endl;
}
void f() {
shared_ptr<B> p(this);
cout << p->x_ << endl;
//shared_from_this();
}
private:
int x_;
};
/*
*
*/
int main(int argc, char** argv) {
shared_ptr<B> x(new B);
x->f();
return 0;
}
编译通过,但是运行结果:
[cpp]
B::B()
4
B::~B()
B::~B()
两次析构B对象,这是个灾难。
现在试一下enable_shared_from_this:
[cpp]
class A : public enable_shared_from_this<A> {
public:
A() {
cout << "A::A()" << endl;
}
~A() {
cout << "A::~A()" << endl;
}
void f() {
//cout << shared_from_this()->x_ << endl; // this way is okay too
shared_ptr<A> p = shared_from_this();
cout << p->x_ << endl;
}
private:
int x_;
};
/*
*
*/
int main(int argc, char** argv) {
shared_ptr<A> x(new A);
x->f();
return 0;
}
运行结果:
[cpp]
A::A()
0
A::~A()
那么,为什么需要这样做呢?在自己的类里面访问自己的成员,其实只是个示例代码,一定必要都没有。
不过有一种可能,就是f函数需要返回自己的指针给调用者,难道这样写么?
[cpp]
A* f();
一个裸指针返回出去,失控了。谁也不知道调用者会干什么?
比较聪明的方法是设计成:
shared_ptr<A> f()
好了,这就是为什么我们需要enable_shared_from_this。
- enable_share_from_this功能介绍
- enable_share_from_this功能介绍
- enable_share_from_this功能介绍
- enable_share_from_this功能介绍
- enable_share_from_this
- enable_share_from_this
- enable_share_from_this
- 为何会有enable_share_from_this
- 为何会有enable_share_from_this
- Boost.Smart_ptr/enable_share_from_this笔记
- 为何会有enable_share_from_this
- enable_share_from_this 模板类使用和完全解析
- 交叉销售功能介绍-功能
- jdbc部分功能介绍
- Code Assist功能介绍
- 接口功能介绍
- Windows系统还原功能介绍
- Vim功能介绍
- 正则表达式---获取英文双引号里面的内容
- 国外 2D 引擎相关站点收集
- 网站建设优化如何做好内部页面的优化
- 解决错误:/gen already exists but is not a source folder. Convert to a source folder or rename it
- 开始iOS 7中自动布局教程(一)
- enable_share_from_this功能介绍
- JavaScript权威指南学习笔记——JavaScript概述
- 字符串加密处理
- 黑马程序员--包与包之间的调用
- android2与android4在网络连接上的一点差异
- python 文件打开和关闭
- [jQueyr]选择器
- 第十六周 利用函数和指针对两个数字进行交换
- 发现一个初学者的服务器学习网站,很好!