enable_shared_from_this允许类共享内部指针

文章介绍了enable_shared_from_this模板类的用法,通过在TcpConnection类中继承此模板,允许在类内部安全地使用shared_ptr。示例展示了如何通过shared_from_this()方法获取指向类实例的shared_ptr,常用于在类的方法中创建线程池或者传递对象给其他组件。
摘要由CSDN通过智能技术生成

这里写自定义目录标题

enable_shared_from_this用法

下面展示部分代码:

class TcpConnection : public std::enable_shared_from_this<TcpConnection>
{ // 允许安全使用shared_ptr

public:
    typedef std::shared_ptr<TcpConnection> spTcpConnection;  // 指向TcpConnection的智能指针
    
   ……

    spTcpConnection sptcpconn = shared_from_this();
    
	……


类TcpConnection通过公有继承std::enable_shared_from_this结构,进而可以在其所属函数内通过shared_from_this()函数得到一个类型为std::shared_ptr智能指针sptcpconn,该智能指针指向这个类实体本身。
这样就能在这个类实体内将这个智能指针作为参数传递出类函数到其他作用域,常见用法是作为线程池参数传出。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用enable_shared_from_this需要遵循以下步骤: 1. 定义一个并继承自std::enable_shared_from_this<T> 2. 在的构造函数中,将this指针传递给std::shared_ptr<T>对象。 3. 在需要使用shared_from_this()的地方,调用该函数,并将返回值赋值给一个std::shared_ptr<T>对象。 以下是一个示例代码: ``` #include <memory> #include <iostream> class MyClass : public std::enable_shared_from_this<MyClass> { public: MyClass(int val) : m_val(val) {} std::shared_ptr<MyClass> getShared() { return shared_from_this(); } int getValue() const { return m_val; } private: int m_val; }; int main() { std::shared_ptr<MyClass> ptr1(new MyClass(10)); std::shared_ptr<MyClass> ptr2 = ptr1->getShared(); std::cout << "ptr1 value: " << ptr1->getValue() << std::endl; std::cout << "ptr2 value: " << ptr2->getValue() << std::endl; return 0; } ``` 在这个例子中,我们定义了一个名为MyClass的,这个继承自std::enable_shared_from_this<MyClass>。在的构造函数中,我们将this指针传递给std::shared_ptr<MyClass>对象。在getShared()函数中,我们调用shared_from_this()函数,并将返回值赋值给一个std::shared_ptr<MyClass>对象。 最后,我们创建了两个std::shared_ptr<MyClass>对象,一个是直接使用new操作符创建的,另一个是通过getShared()函数获取的。我们输出了这两个对象的值,可以看到它们都指向同一个对象,并且该对象的值为10。这说明了两个std::shared_ptr<MyClass>对象共享同一个对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

邱邱玩编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值