首页 > 编程语言 >C++11中enable_shared_from_this的用法解析

C++11中enable_shared_from_this的用法解析

时间:2022-11-14 15:12:05浏览次数:61  
标签:11 std enable weak C++ __ shared ptr

转载:https://blog.csdn.net/breadheart/article/details/112451022

什么是 enable_shared_from_this?

下面摘自 cpp reference 中概述

C++11 开始支持 enable_shared_from_this,它是一个模板类,定义在头文件 <memory>,其原型为:
template< class T > class enable_shared_from_this;

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::shared_from_this 成员函数,将会返回一个新的 std::shared_ptr 对象,它与 pt 共享 t 的所有权。

为什么要用 enable_shared_from_this?

  1. 需要在类对象的内部中获得一个指向当前对象的 shared_ptr 对象。(当 T 类的对象 t 被一个为名为 pt 的 std::shared_ptr 类对象管理时)
  2. 如果在一个程序中,对象内存的生命周期全部由智能指针来管理。在这种情况下,要在一个类的成员函数中,对外部返回 this 指针就成了一个很棘手的问题。

什么时候用?

  • 当一个类被共享智能指针 share_ptr 管理,且在类的成员函数里需要把当前类对象作为参数传给其他函数时,这时就需要传递一个指向自身的 share_ptr。

如何安全地将 this 指针返回给调用者?

  • 一般来说,我们不能直接将 this 指针返回。如果函数将 this 指针返回到外部某个变量保存,然后这个对象自身已经析构了,但外部变量并不知道,此时如果外部变量再使用这个指针,就会使得程序崩溃。

标准库中的源码

  template<typename _Tp>
    class enable_shared_from_this
    {
    protected:
      // 构造函数
      constexpr enable_shared_from_this() noexcept { }
      
      // 拷贝构造函数
      enable_shared_from_this(const enable_shared_from_this&) noexcept { }
      
      // 赋值操作
      enable_shared_from_this&
      operator=(const enable_shared_from_this&) noexcept
      { return *this; }
      
      // 析构函数
      ~enable_shared_from_this() { }

    public:
      // 成员函数,返回类型为共享智能指针 shared_ptr
      shared_ptr<_Tp>
      shared_from_this()
      { return shared_ptr<_Tp>(this->_M_weak_this); }
      
      // const 类型的成员函数
      shared_ptr<const _Tp>
      shared_from_this() const
      { return shared_ptr<const _Tp>(this->_M_weak_this); }

#if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11
#define __cpp_lib_enable_shared_from_this 201603
     // 成员函数,返回类型为弱类型的智能指针 weak_ptr
      weak_ptr<_Tp>
      weak_from_this() noexcept
      { return this->_M_weak_this; }
      
      // const 类型的成员函数
      weak_ptr<const _Tp>
      weak_from_this() const noexcept
      { return this->_M_weak_this; }
#endif

    private:
      // 函数模板
      template<typename _Tp1>
    void
    _M_weak_assign(_Tp1* __p, const __shared_count<>& __n) const noexcept
    { _M_weak_this._M_assign(__p, __n); }

      // Found by ADL when this is an associated class.
      friend const enable_shared_from_this*
      __enable_shared_from_this_base(const __shared_count<>&,
                     const enable_shared_from_this* __p)
      { return __p; }

      template<typename, _Lock_policy>
    friend class __shared_ptr;

      mutable weak_ptr<_Tp>  _M_weak_this;
    };
  • enable_shared_from_this 类中的成员函数
  1. (constructor):构造一个 enable_shared_from_this 对象,是一个受保护的成员函数,成员属性为 protected。
  2. (destructor):销毁一个 enable_shared_from_this 对象,是一个受保护的成员函数,成员属性为 protected。
  3. operator=:返回到 this 的引用,是一个受保护成员函数,成员属性为 protected。
  4. shared_from_this:返回共享 *this 指针所有权的 shared_ptr,是一个 public 属性的成员函数。
  5. weak_from_this(C++17):返回共享 *this 所指针有权的 weak_ptr,是一个public 属性的成员函数。
  • 具体的代码示例
#include <iostream>
#include <stdlib.h>
#include <memory>
using namespace std;

// 比较推荐的写法
struct Good : std::enable_shared_from_this<Good> // note: public inheritance
{
    std::shared_ptr<Good> getptr() {
        return shared_from_this();
    }
};

// 错误的用法:用不安全的表达式试图获得 this 的 shared_ptr 对象
struct Bad
{
    std::shared_ptr<Bad> getptr() {
        return std::shared_ptr<Bad>(this);
    }
    ~Bad() { std::cout << "Bad::~Bad() called\n"; }
};
 
int main()
{
    // 正确的用法: 两个 shared_ptr 共享同一个对象
    std::shared_ptr<Good> gp1 = std::make_shared<Good>();
    std::shared_ptr<Good> gp2 = gp1->getptr();
    std::cout << "gp2.use_count() = " << gp2.use_count() << '\n';
 
    // 错误的用法: 调用 shared_from_this 但其没有被 std::shared_ptr 占有 
    try {
        Good not_so_good;
        std::shared_ptr<Good> gp1 = not_so_good.getptr();
    } 
    catch(std::bad_weak_ptr& e) {
        // 在 C++17 之前,编译器不能捕获 enable_shared_from_this 抛出的std::bad_weak_ptr 异常
        // 这是在C++17之后才有的特性
        std::cout << e.what() << '\n';    
    }
 
    // 错误的用法,每个 shared_ptr 都认为自己是对象的唯一拥有者
    // 调用错误的用法,会导致两次析构 Bad的对象,第二次析构时,指针指向的空间已经被析构,
    // 会导致程序出错
    std::shared_ptr<Bad> bp1 = std::make_shared<Bad>();
    std::shared_ptr<Bad> bp2 = bp1->getptr();
    std::cout << "bp2.use_count() = " << bp2.use_count() << '\n';

    return 0;
}  

 

使用注意事项

  • enable_shared_from_this 的常见实现为:其内部保存着一个对 this 的弱引用(例如 std::weak_ptr )。 std::shared_ptr 的构造函数检测无歧义且可访问的 (C++17 起) enable_shared_from_this 基类,并且若内部存储的弱引用没有被以存在的 std::shared_ptr 占有,则 (C++17 起)赋值新建的 std::shared_ptr 为内部存储的弱引用。为另一个 std::shared_ptr 所管理的对象构造一个 std::shared_ptr ,将不会考虑内部存储的弱引用,从而将导致未定义行为(undefined behavior)。
  • 只允许在先前已被std::shared_ptr 管理的对象上调用 shared_from_this 。否则调用行为未定义 (C++17 前)抛出 std::bad_weak_ptr 异常(通过 shared_ptr 从默认构造的 weak_this 的构造函数) (自C++17 起)。
  • enable_shared_from_this 提供安全的替用方案,以替代 std::shared_ptr(this) 这样的表达式(这种不安全的表达式可能会导致 this 被多个互不知晓的所有者析构)。

参考

————————————————
版权声明:本文为CSDN博主「飞狼说」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/breadheart/article/details/112451022

标签:11,std,enable,weak,C++,__,shared,ptr
From: https://www.cnblogs.com/hansjorn/p/16889081.html

相关文章

  • C++中sort函数、1.4最长公共子串
    sort()即为用来排序的函数,它根据具体情况使用不同的排序方法,效率较高。sort在实现时避免了经典快速排序中可能出现的会导致实际复杂度退化到O(n2)的极端情况。使用sort()......
  • 使用 C++ 部署深度学习模型快速上手方案
    本文将从获取一个训练好的 shufflenet_v2 模型出发,讲解如何使用MegEngineLite的C++接口将其部署到CPU(Linuxx86/AndroidArm)环境下运行。主要分为以下小节:导......
  • 2022/11 LeetCode练习
    ......
  • 11.14.2
    #include<stdio.h>intmain(){ intn,i,j,h; inta[100]; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } intmax=a[0]; for(i=0;i<n;i++){ ......
  • 11.14.3
    #include<stdio.h>intmain(){ inti,j; inty1,y2,count=0; scanf("%d%d",&y1,&y2); for(i=y1;i<=y2;i++) {if(i%4==0&&i%100!=0||i%400==0){printf("%d",i);count......
  • C和C++的区别
    一、面向过程语言和面向对象语言C语言是面向过程语言,而C++是面向对象语言(一)面向过程和面向对象的区别(1)面向过程:面向过程编程就是分析出解决问题的步骤,然后把这些步骤一......
  • 竟然还有人迷信双11销售数据(ZZ)
    竟然还有人迷信双11销售数据https://www.t66y.com/user/gtechzf居然还有人相信双11天猫的数据。这么说吧,双11的销售金额是真实的,但各品牌的实际销售是假的。所谓成交金额......
  • C++ 位运算Bitwise operations详解 ----- 重要的解题技巧
    什么是位运算:利用位运算符号进行二进制位计算的操作即为位运算维基百科:......
  • 2022.11.14 No.2 Leetcode
    重庆昨天新增已经破2000。晚上回去研究了一下家里老台式改服务器的可行性,感觉问题不大,就是可能要给家里换组电力猫了。今天降温了,要不是寝室里有个从早到晚......
  • CSP 202209-1 如此编码 C++
     链接1#include<iostream>2#include<vector>34intmain(){5intx{},m{};6std::cin>>x>>m;7std::vector<std::vector<int>>nc......