我正在尝试在asio中保持已连接客户端的列表。 我从文档中调整了聊天服务器示例(http://www.boost.org/doc/libs/1_57_0/doc/html/boost_asio/example/cpp03/chat/chat_server.cpp),以下是我最终得出的重要部分:
#include <iostream>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <set>
using boost::asio::ip::tcp;
class tcp_connection;
std::set<boost::shared_ptr<tcp_connection>> clients;
void add_client(boost::shared_ptr<tcp_connection> client)
{
clients.insert(client);
}
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
tcp_connection(boost::asio::io_service& io_service) : socket_(io_service)
{
}
tcp::socket socket_;
void start()
{
add_client(shared_from_this());
}
tcp::socket& socket()
{
return socket_;
}
};
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), 6767))
{
tcp_connection* new_connection = new tcp_connection(io_service_);
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::start_accept, this, new_connection,
boost::asio::placeholders::error));
}
private:
void start_accept(tcp_connection* new_connection,
const boost::system::error_code& error)
{
if (!error)
{
new_connection->start();
new_connection = new tcp_connection(io_service_);
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::start_accept, this, new_connection,
boost::asio::placeholders::error));
}
}
boost::asio::io_service& io_service_;
tcp::acceptor acceptor_;
};
int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server(io_service);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
在调用shared_from_this()
时,我的服务器崩溃并显示以下消息:
异常:tr1::bad_weak_ptr
我已经做了一些搜索,似乎shared_from_this()
很特别,但我似乎找不到需要更改的确切内容。
new
的结果存储在一个裸指针中,只是为了稍后使用shared_from_this()
呢?看起来你的设计可以简化,从而完全消除这个问题。 - John Zwinckenable_shared_from_this
的 Boost 文档中提到:“必须存在至少一个拥有 t 的 shared_ptr 实例 p”,而你似乎没有这个实例。 - Jonathan Pottershared_from_this
创建更多对象之前,您需要已经拥有一个持有该对象的shared_ptr
。虽然我自己从未使用过它,所以这只是一个猜测。 - Jonathan Pottershared_from_this
才有意义。否则,不可能拥有一个lifetime保证至少与对象寿命一样长的shared pointer,而shared_from_this
的唯一目的就是返回这样的指针。因此,总之,你正在要求shared_from_this
去做不可能的事情。 - David Schwartz