为正在执行的程序创建客户端类时遇到了问题。
我在标题中定义了类,如下所示:
class Client {
public:
Client();
private:
tcp::socket socket;
boost::asio::io_context io_context;
tcp::resolver resolver;
tcp::resolver::results_type endpoints;
};
但是,在构造类时,程序因与套接字初始化相关的错误而崩溃。
这是类的构造函数:
Client::Client() : resolver(io_context), endpoints(resolver.resolve("localhost", "daytime")), socket(io_context) { // Error here.
try {
boost::asio::connect(socket, endpoints);
}
catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
调用堆栈从客户端类到basic_socket以及其他一些boost类,直到到达win_mutex,该程序最终因溢出错误而崩溃。
我在做错什么吗?
答案 0 :(得分:0)
(由于两天内没有人发表评论,所以感到很高兴,感谢G.M的帮助)
问题在于变量的初始化顺序。先声明socket
会导致问题。
要修复,我只需要更改此内容:
class Client {
public:
Client();
private:
tcp::socket socket;
boost::asio::io_context io_context;
tcp::resolver resolver;
tcp::resolver::results_type endpoints;
};
对此:
class Client {
public:
Client();
private:
boost::asio::io_context io_context;
tcp::resolver resolver;
tcp::resolver::results_type endpoints;
tcp::socket socket; // Note the order of the variable declaration
};