boost的一个错误error C2512

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.

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值