应用程序结束时boost :: shared_ptr崩溃

时间:2013-06-14 07:27:49

标签: c++ shared-ptr

我有以下课程:

    class Session
    {
    public:      
      Session(boost::asio::io_service &io_service)
        : socket_(io_service)
      {
      }
    }



class ConnectionHandler: public boost::enable_shared_from_this<ConnectionHandler> {
         boost::shared_ptr<Session> mySession;
                //blah blah
  Broker &theBroker;
  public:    
 //....    
 ConnectionHandler(
       boost::shared_ptr<Session> session_ ,/*....*/);   
       ~ConnectionHandler(){
        //crash happens here  
        std::cout << "Killing ConnectionHandler " << this << " " << shared_from_this();
                }    
//.... 
};  



class ClientHandler: public EventListener {   
Broker & broker;   
//... 
public:   
ClientHandler(Broker &);
   boost::shared_ptr<ConnectionHandler > cnnHandler;
//...   
virtual ~ClientHandler();
//... 
};

(session是ConnectionHandler的成员,ConnectionHandler是ClientHandler的成员)

好吧,对象是这样创建的:

xxx::some_function()
{
//...
boost::shared_ptr<ClientHandler> clientEntry(new ClientHandler(broker));
boost::shared_ptr<ConnectionHandler > cnnHandler(
                new ConnectionHandler(request.session_,broker
            //...blah blah
            )
                    );
//and now assign it
clientEntry->cnnHandler = cnnHandler;

//and then insert it to a nested std::map container somewhere else
broker.insertClientList(clientEntry);
}//and clientEntry & cnnHandler go out of scope

应用程序运行良好但最终崩溃说:

terminate called after throwing an instance of'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> >'
      what():  tr1::bad_weak_ptr

另一个注意事项:我在应用程序崩溃的地方标记了析构函数。如果我没有输入std :: cout,那么应用程序会在~session()

中崩溃

我可以知道我做错了吗?我怎么解决呢?

谢谢

1 个答案:

答案 0 :(得分:3)

你永远不应该在d-tor中调用shared_from_this

https://svn.boost.org/trac/boost/ticket/147

此行为是设计使然。因为析构函数会破坏 对象,创建一个shared_ptr是不安全的 一旦析构函数结束就会变得悬空。