C++11中模板类std::enable_shared_from_this的使用
C++11中的模板类template <class T> class enable_shared_from_this功能:允许从std::enable_shared_from_this派生的类T的对象创建指向自身的shared_ptr实例并与现有的shared_ptr对象共享所有权。T需要为完整类型,通常是final的。如果使用this创建一个新的shared_ptr,则其与现有的shared_ptr所有者不同,从而会导致无效引用或导致此对象被删除多次。
std::enable_shared_from_this能让其一个对象(假设其名为t,且已被一个std::shared_ptr对象pt管理)安全地生成其它额外的std::shared_ptr实例(假设名为pt1, pt2, …),它们与pt共享对象t的所有权。
若一个类T继承std::enable_shared_from_this<T>,则会为该类T提供成员函数:shared_from_this。当T类型对象t被一个名为pt的std::shared_ptr<T>类对象管理时,调用T::shared_from_this成员函数,将会返回一个新的std::shared_ptr<T>对象,它与pt共享t的所有权。
以下为测试代码:
namespace {
struct C : std::enable_shared_from_this<C> {};struct Best : std::enable_shared_from_this<Best> { // note: public inheritancestd::shared_ptr<Best> getptr() { return shared_from_this(); }// No public constructor, only a factory function, so there's no way to have getptr return nullptr.
#ifdef _MSC_VERstatic std::shared_ptr<Best> create() // nodiscard need compiler flags: "/std:c++17"
#else[[nodiscard]] static std::shared_ptr<Best> create()
#endif{// Not using std::make_shared<Best> because the c'tor is private.return std::shared_ptr<Best>(new Best());}private:Best() = default;
};class Y: public std::enable_shared_from_this<Y> {
public:std::shared_ptr<Y> f(){return shared_from_this(); // returns a valid shared_ptr, even though it had no member instance//return std::shared_ptr<Y>(this); // error}
};class Foo : public std::enable_shared_from_this<Foo> {
public:Foo() = default;~Foo() {}void set_name(std::string name) { name_ = name; }void set_age(int age) { age_ = age; }const std::string& get_name() const { return name_; }int get_age() const { return age_; }private:std::string name_;int age_;
};void modify_foo(std::shared_ptr<Foo> foo)
{foo->set_name("Tom");foo->set_age(10);fprintf(stdout, "modify_foo use count: %d\n", foo.use_count()); // 2
}} // namespaceint test_enable_shared_from_this_1()
{// reference: http://www.cplusplus.com/reference/memory/enable_shared_from_this/std::shared_ptr<C> foo, bar;foo = std::make_shared<C>();bar = foo->shared_from_this();if (!foo.owner_before(bar) && !bar.owner_before(foo))fprintf(stdout, "foo and bar share ownership\n");return 0;
}int test_enable_shared_from_this_2()
{// reference: https://en.cppreference.com/w/cpp/memory/enable_shared_from_this// Best: Same but can't stack-allocate it:std::shared_ptr<Best> best0 = Best::create();std::shared_ptr<Best> best1 = best0->getptr();fprintf(stdout, "best0.use_count: %d, best1.use_count: %d\n", best0.use_count(), best1.use_count()); // 2, 2//Best stackBest; // <- Will not compile because Best::Best() is private.return 0;
}int test_enable_shared_from_this_3()
{// reference: https://stackoverflow.com/questions/712279/what-is-the-usefulness-of-enable-shared-from-this// It enables you to get a valid shared_ptr instance to this, when all you have is this. // Without it, you would have no way of getting a shared_ptr to this, unless you already had one as a member.std::shared_ptr<Y> p(new Y);std::shared_ptr<Y> q = p->f();if (!(p == q)) {fprintf(stderr, "p should be equal to q\n");return -1;}if (p < q || q < p) { // p and q must share ownershipfprintf(stderr, "p and q must share ownership\n");return -1;}return 0;
}int test_enable_shared_from_this_4()
{std::shared_ptr<Foo> foo = std::make_shared<Foo>();foo->set_name("Take");foo->set_age(20);fprintf(stdout, "foo use count: %d, name: %s, age: %d\n", foo.use_count(), foo->get_name().c_str(), foo->get_age()); // 1, Take, 20modify_foo(foo->shared_from_this());fprintf(stdout, "foo use count: %d, name: %s, age: %d\n", foo.use_count(), foo->get_name().c_str(), foo->get_age()); // 1, Tom, 10return 0;
}
GitHub:https://github.com/fengbingchun/Messy_Test
C++11中模板类std::enable_shared_from_this的使用相关推荐
- C++多线程中互斥量std::mutex与模板类std::lock_guard
一. 互斥量std::mutex C++中通过实例化std::mutex创建互斥量实例,通过成员函数lock()对互斥量上锁,unlock()进行解锁.C++中与std::mutex相关的类(包括锁类 ...
- C++中模板类的静态成员
目录 C++中模板类的静态成员 为什么需要模板类的静态成员? 代码示例 C++中模板类的静态成员 为什么需要模板类的静态成员? 模板类的静态成员和普通类,普通函数的静态成员一样,我们想在函数调用后留些 ...
- 标准布局类(11中布局类)
2019独角兽企业重金招聘Python工程师标准>>> <div class="box"><div id="myAuto" ...
- C++中模板类使用友元模板函数 和友员非模版函数!使用不当出现编译错误:无法解析的外部符号…
在c++海大本科课程设计的最后章节(模板使用 )中涉及到了在Mat类模板中定义友元函数friend Mat<T> operator+(Mat<T> &m, T num) ...
- c++11中static类对象构造函数线程安全
该博文为原创文章,未经博主同意不得转载,如同意转载请注明博文出处 本文章博客地址:https://cplusplus.blog.csdn.net/article/details/105113421 s ...
- C++中模板类中的成员函数以及模板函数在类外定义
在C++中,类中的成员函数可以在类外完成定义,从而显得类中的成员函数看起来简洁明了.但是模板类里的成员函数和模板函数与普通的成员函数在类外定义不同. 先定义一个模板类以及成员函数和模板函数: 接下我们 ...
- 【C++11 】模板类array对象的使用方法
目录 1.总体理解array 2.具体理解array 3.array程序示例 1.总体理解array C和C++创建数组时,通常会使用new和delete来管理空间 C++11提供了 一种新的思路,# ...
- C++11中Thread类简单使用的例子
代码如下: #include <iostream> #include <thread> #include <chrono> #include <future& ...
- C++中模板类map常用示例
#include <iostream> #include <map>using namespace std;int main() {/********************* ...
最新文章
- 聊聊Synchronized
- rtp rtcp rtsp
- pytorch:固定部分层参数,固定单个模型
- 漫步最优化十——极值类型
- Python+OpenCV:直方图均衡化(Histogram Equalization)
- 股指期货开户的条件和流程
- SCTF | 三足鼎立焦点对抗,天枢战队有惊无险斩获冠军头衔
- ThreadPoolExecutor(六)——线程池关闭之后
- jenkins 403 No valid crumb was included in the request 解决方案
- 链上天眼2.0版本上线,欧科云链深耕区块链大数据产业成绩斐然
- quartz 2D 总结
- dom4j 学习 -- 封装dom4j工具类+如何使用dom4j解析
- Android之ContextMenu
- Win10 常用快捷键总结
- 2022电工(初级)考试试题及答案
- 为什么 Java 与 Python 在对待成员变量的访问控制方式截然相反?
- 19-你知道哪几种锁?分别有什么特点?
- 潮流分析matlab课程设计小结,电力系统暂态分析课程设计--基于MATLAB的电力系统复杂潮流分析...
- Qt添加资源文件,为QAction添加图标,建立信号槽函数并实现
- 【问题处理】如何查看端口号是否被占用
热门文章
- 笔记本电脑怎么重装系统Win7?给你10分钟能完成系统重装吗?
- 图片处理:将JPEG格式批量修改为JPG格式
- Taro3.x 快速开发微信小程序以及 minidebug 小程序调试工具使用
- 最简单的 MyBatis Plus 的多表联接、分页查询实现方法
- Linux中 top命令详解
- Unity5.x制作合金弹头(一)-DoTween组件的使用
- ARM裸机的知识点总结---------10、解决X210开发板软开关按键问题( 引脚功能复用)
- ygo游戏王卡组_游戏王卡组第六弹:游戏衍生卡组最风光的卡组之一,完全碾压社长...
- 如何解决Windows10系统开机提示,没有默认的邮件客户端
- 搭建powerpc交叉编译工具链