@@ -67,20 +67,6 @@ TcpClient::TcpClient(EventLoop *loop,
67
67
connect_(true )
68
68
{
69
69
(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
- });
84
70
LOG_TRACE << " TcpClient::TcpClient[" << name_ << " ] - connector " ;
85
71
}
86
72
@@ -110,6 +96,23 @@ void TcpClient::connect()
110
96
// TODO: check state
111
97
LOG_TRACE << " TcpClient::connect[" << name_ << " ] - connecting to "
112
98
<< 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
+ });
113
116
connect_ = true ;
114
117
connector_->start ();
115
118
}
0 commit comments