boost 的一个错误
boost::asio::basic_stream_socket<Protocol>' : no appropriate default constructor available
问题重现:
class SocketClient { private: int port; //Port, currently unused boost::asio::io_service io_service; boost::asio::ip::tcp::resolver::iterator endpoint_iterator; boost::asio::ip::tcp::socket sock; //This causes the error //It wants to be like this (impossible too): //boost::asio::ip::tcp::socket sock(io_service); public: void init(const char*, const char* ); SocketClient(); //Default constructor bool connect(); bool read(int bytes, char *text); bool send(int length, char *text); bool send(std::string text); unsigned int timeout; }; And here is the constructor: SocketClient::SocketClient() { //ERROR: (23): error C2512: 'boost::asio::basic_stream_socket<Protocol>' : no appropriate default constructor available sock=boost::asio::ip::tcp::socket(io_service); //Adding this didn't help }
解决方法:
SocketClient::SocketClient() : sock(io_service) { // Other initialization code here... }
原因:
Be careful though: this is well-defined because member variables are constructed in the order they appear in the class definition, and io_service
appears before sock
. If that wasn't the case, you would pass an uninitialized object to the constructor of socket
, most likely resulting in Undefined Behavior.