Boost async_accept导致“访问冲突” - 错误

时间:2011-05-24 23:37:24

标签: c++ boost boost-asio

Server::Server(boost::asio::io_service& io_service,std::string ip,short port,std::shared_ptr<ConnectionFactory> factory)
    : acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string(ip.data()), port)){

        m_factory = factory;
        start_accept();

        std::cout<<"Socket accepting connections..."<<std::endl;
}

void Server::start_accept(){
    boost::asio::io_service io_service;
    std::shared_ptr<Connection> conn = m_factory->create(io_service);

    acceptor_.async_accept(conn->socket(),
        boost::bind(&Server::handle_accept, this,conn,
          boost::asio::placeholders::error));

}


void Server::handle_accept(std::shared_ptr<Connection> conn,const boost::system::error_code& error){

    if (!error)
    {
        std::cout<<"on connected"<<std::endl;
        conn->OnConnected();
        start_accept();
    }
  }

当我运行项目时,我收到以下错误:

Access violation reading location 0xfeeeff02.

此错误的原因是什么?

1 个答案:

答案 0 :(得分:3)

io_service start_accept()超出了Server::Server( ... ) { m_factory = factory; start_accept(); std::cout<<"Socket accepting connections..."<<std::endl; } void Server::start_accept() { boost::asio::io_service io_service; ^^^^^^^^^ std::shared_ptr<Connection> conn = m_factory->create(io_service); acceptor_.async_accept(conn->socket(), boost::bind(&Server::handle_accept, this,conn, boost::asio::placeholders::error)); } 的范围,这是不好的,可能不是你想要的。

更改此

Server::Server( ... ) {   
        m_factory = factory;
        start_accept( io_service );
                      ^^^^^^^^^

        std::cout<<"Socket accepting connections..."<<std::endl;
}

void Server::start_accept( const boost::asio::io_service& io_service ){
    std::shared_ptr<Connection> conn = m_factory->create(io_service);

    acceptor_.async_accept(conn->socket(),
        boost::bind(&Server::handle_accept, this,conn,
          boost::asio::placeholders::error));

}

到这个

{{1}}

但是,正如您的评论所暗示的那样,您真的应该发布一个问题的自包含示例。以上建议是我最好的猜测。