shared_from_this 和这个的用例
Use case of shared_from_this and this
在this source file中有两个类:tcp_connection
和tcp_server
。在我看来,我已经选择了相关的代码位,但您可能想参考完整的源代码以获取更多信息。
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
void start()
{
message_ = make_daytime_string();
boost::asio::async_write(socket_, boost::asio::buffer(message_),
boost::bind(&tcp_connection::handle_write, shared_from_this()));
}
};
class tcp_server
{
private:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(acceptor_.get_io_service());
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
};
我的问题很简单:我们会在 async_write
函数中使用 shared_from_this
作为 bind
参数并使用 this
作为 bind
参数在
async_accept
函数中?
共享指针管理动态分配对象的生命周期。每个持有的指针都会增加一个 引用计数 ,当所有持有的指针都消失时,引用的对象将被释放。
服务器
只有一台服务器,而且不是动态分配的。相反,该实例比接受器(可能还有 io_service)的寿命更长,因此没有任何异步操作可以相信该对象能够存活足够长的时间。
连接
每个客户端生成一个新连接,动态分配 (make_shared) 一个 tcp_connection
实例,然后在其上启动异步操作。
服务器不会保留共享指针的副本,因此当连接上的所有异步操作完成时(例如,因为连接已断开)tcp_connection
对象将被释放。
然而,因为对象必须 而不是 在异步操作进行时被销毁,您需要将完成处理程序绑定到共享指针 (shared_from_this
)共 this
.
在this source file中有两个类:tcp_connection
和tcp_server
。在我看来,我已经选择了相关的代码位,但您可能想参考完整的源代码以获取更多信息。
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
void start()
{
message_ = make_daytime_string();
boost::asio::async_write(socket_, boost::asio::buffer(message_),
boost::bind(&tcp_connection::handle_write, shared_from_this()));
}
};
class tcp_server
{
private:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(acceptor_.get_io_service());
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
};
我的问题很简单:我们会在 async_write
函数中使用 shared_from_this
作为 bind
参数并使用 this
作为 bind
参数在
async_accept
函数中?
共享指针管理动态分配对象的生命周期。每个持有的指针都会增加一个 引用计数 ,当所有持有的指针都消失时,引用的对象将被释放。
服务器
只有一台服务器,而且不是动态分配的。相反,该实例比接受器(可能还有 io_service)的寿命更长,因此没有任何异步操作可以相信该对象能够存活足够长的时间。
连接
每个客户端生成一个新连接,动态分配 (make_shared) 一个 tcp_connection
实例,然后在其上启动异步操作。
服务器不会保留共享指针的副本,因此当连接上的所有异步操作完成时(例如,因为连接已断开)tcp_connection
对象将被释放。
然而,因为对象必须 而不是 在异步操作进行时被销毁,您需要将完成处理程序绑定到共享指针 (shared_from_this
)共 this
.