boost:asio 联接管理3

boost::asio 连接管理3

现在用newLISP编写TCP客户端来测试程序:

chenshu@chenshu-beijing:~$ newlisp
newLISP v.10.4.5 64-bit on Linux IPv4/6 UTF-8 libffi, execute 'newlisp -h' for more info.

> (set 'socket (net-connect "localhost" 8888))
3
> (net-send socket "a")

上面的代码略做解释:

1.(net-connect ...) 用来连接本地8888端口,返回的socket文件被赋值给了socket变量

2.(net-send可以对socket代表的连接发送字符串"a"


此时服务程序打印如下;

chenshu@chenshu-beijing:~/NetBeansProjects/CppApplication_4/dist/Debug/GNU-Linux-x86$ ./cppapplication_4 
count1:1
count2:2
count3:2
The new connection object is starting now.
~Connection
Operation canceled
count3:2

注意到了么,Connection的析勾函数被调用后,居然它的成员函数AfterReadChar还会被调用。错在哪里?

因为之前

async_read(socket, buffer(read_buffer_),  
           boost::bind(&Connection::AfterReadChar, this, _1));  
绑定了this指针。所以即便shared_ptr的引用计数为0导致析勾函数被调用,而this指针由于被bind_t保存,所以asio框架仍然能够调用到这个被删除的对象的成员函数。

这种行为是可怕的,因为下次可能就是程序崩溃。关键问题是应该还是将shared_ptr拿去绑定,这样只要一切都在shared_ptr的管理内,asio就不会错误的调用已经被销毁的对象。


所以下一篇就要解决这个问题。