博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Effective C++: std::enable_shared_from_this
阅读量:7228 次
发布时间:2019-06-29

本文共 915 字,大约阅读时间需要 3 分钟。

hot3.png

当一个类对象(class)被智能指针管理的时候,且需要在类内定义一个成员函数返回自身的时候.

 #include 
#include 
#include 
class Widget;std::vector
> widgets;class Widget{ private: int number; public: Widget(const int& n):number(n){} ~Widget() { std::cout<<"destroy"<
(this));}class Rectangle : public std::enable_shared_from_this
{ private: int number; public: Rectangle(const int& n):number(n){} ~Rectangle(){ std::cout<<"destroy"<
ptr = this->shared_from_this(); std::cout<
number<
third(new Rectangle(30)); std::shared_ptr
forth = third->shared_from_this(); forth->get_shared(); //ok. //second.get_shared(); //error.因为此时的std::enable_shared_from_this处于未初始化状态. Rectangle* fifth = second.get_this(); //返回自身这样其实是和前面的shared_from_this效果一样的,但是很可能产生一些 //但是这样直接传递出来一个裸露的指针很容易产生破坏的行为. std::cout<
<<" "<
<

 

转载于:https://my.oschina.net/SHIHUAMarryMe/blog/661963

你可能感兴趣的文章
Python 爬虫十六式 - 第六式:JQuery的假兄弟-pyquery
查看>>
宜昌a货翡翠,包头a货翡翠
查看>>
【微信事业群】趣味面试算法题
查看>>
保守的国美再一次进击社交电商,前途未卜?
查看>>
git
查看>>
Python学习教程(Python学习路线):Python 3—手动创建迭代器
查看>>
说说如何在 Virtual Box 中新建 CentOS 虚拟机
查看>>
Cordova + Vue 实现点击两次退出应用
查看>>
JAVA 多用户商城系统b2b2c-Spring Cloud Stream 介绍
查看>>
spring cloud构建互联网分布式微服务云平台-SpringCloud集成项目简介
查看>>
基于房源的画像分析
查看>>
80% UI 初学者走过的弯路,你走了几条?
查看>>
文档和元素的几何滚动
查看>>
php 设计模式
查看>>
Java springcloud B2B2C o2o多用户商城 springcloud架构(八)springboot整合mongodb
查看>>
3年工作经验的Java程序员面试经过
查看>>
Mysql 批量写入数据,对于这类性能问题,你是如何优化的
查看>>
MySQL无法启动几种常见问题小结
查看>>
阿里CTO:阿里所有技术和产品输出都将必须通过阿里云进行
查看>>
更好用的集群限流功能,Sentinel 发布 v1.4.2
查看>>