在 class 构造时创建套接字时出现问题
Problem when socket is created at class construction
我在为我正在执行的程序创建客户端 class 时遇到问题。
我在 header 中定义了 class,像这样:
class Client {
public:
Client();
private:
tcp::socket socket;
boost::asio::io_context io_context;
tcp::resolver resolver;
tcp::resolver::results_type endpoints;
};
但是,在构建 class 时,程序崩溃并出现与套接字初始化相关的错误。
这是 class 构造函数:
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;
}
}
调用堆栈从客户端 class 转到 basic_socket 和其他一些提升 classes,直到转到 win_mutex,程序最终崩溃溢出错误。
我做错了什么吗?
(我自己回答了,因为两天内评论中没有人回答,感谢 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
};
我在为我正在执行的程序创建客户端 class 时遇到问题。
我在 header 中定义了 class,像这样:
class Client {
public:
Client();
private:
tcp::socket socket;
boost::asio::io_context io_context;
tcp::resolver resolver;
tcp::resolver::results_type endpoints;
};
但是,在构建 class 时,程序崩溃并出现与套接字初始化相关的错误。
这是 class 构造函数:
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;
}
}
调用堆栈从客户端 class 转到 basic_socket 和其他一些提升 classes,直到转到 win_mutex,程序最终崩溃溢出错误。
我做错了什么吗?
(我自己回答了,因为两天内评论中没有人回答,感谢 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
};