@@ -67,20 +67,6 @@ TcpClient::TcpClient(EventLoop *loop,
6767 connect_(true )
6868{
6969 (void )validateCert_;
70- connector_->setNewConnectionCallback (
71- std::bind (&TcpClient::newConnection, this , _1));
72- // WORKAROUND: somehow we got use-after-free error
73- auto guard = std::shared_ptr<TcpClient>(this , [](TcpClient *) {});
74- auto weakPtr = std::weak_ptr<TcpClient>(shared_from_this ());
75- connector_->setErrorCallback ([weakPtr]() {
76- auto ptr = weakPtr.lock ();
77- if (!ptr)
78- return ;
79- if (ptr->connectionErrorCallback_ )
80- {
81- ptr->connectionErrorCallback_ ();
82- }
83- });
8470 LOG_TRACE << " TcpClient::TcpClient[" << name_ << " ] - connector " ;
8571}
8672
@@ -110,6 +96,23 @@ void TcpClient::connect()
11096 // TODO: check state
11197 LOG_TRACE << " TcpClient::connect[" << name_ << " ] - connecting to "
11298 << connector_->serverAddress ().toIpPort ();
99+
100+ auto weakPtr = std::weak_ptr<TcpClient>(shared_from_this ());
101+ connector_->setNewConnectionCallback ([weakPtr](int sockfd) {
102+ auto ptr = weakPtr.lock ();
103+ if (ptr)
104+ {
105+ ptr->newConnection (sockfd);
106+ }
107+ });
108+ // WORKAROUND: somehow we got use-after-free error
109+ connector_->setErrorCallback ([weakPtr]() {
110+ auto ptr = weakPtr.lock ();
111+ if (ptr && ptr->connectionErrorCallback_ )
112+ {
113+ ptr->connectionErrorCallback_ ();
114+ }
115+ });
113116 connect_ = true ;
114117 connector_->start ();
115118}
0 commit comments