1

我有以下课程:

    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() 附近崩溃

我可以知道我在哪里做错了吗?我该如何解决?

谢谢你

4

1 回答 1

3

你永远不应该打电话给shared_from_thisd-tor。

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

此行为是设计使然。由于析构函数将销毁对象,因此为它创建 shared_ptr 是不安全的,因为一旦析构函数结束,它将变得悬空。

于 2013-06-14T07:31:30.113 回答