这里写自定义目录标题
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,该智能指针指向这个类实体本身。
这样就能在这个类实体内将这个智能指针作为参数传递出类函数到其他作用域,常见用法是作为线程池参数传出。