错误:将"常量字符串{又名常量std::<char>basic_string}"作为...丢弃限定符 [-允许]




我正在尝试使用Cpprest sdk(Casablanca)实现Websocket客户端。我成功地建立了 Web 套接字连接并能够发送/接收消息。响应作为 websocket_incoming_message 的实例接收,该实例具有一个方法 extract_string(),其定义是,

_ASYNCRTIMP pplx::task<std::string> web::websockets::client::websocket_incoming_message::extract_string (       )   const

因此它返回常量字符串。

我正在尝试将此字符串分配给函数本地字符串变量,以便我可以将其返回到调用方法。但是,我收到以下错误,

error: passing ‘const string {aka const std::basic_string<char>}’ as ‘this’ argument of ‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’ discards qualifiers [-fpermissive]

下面是我的代码块,

std::string WebSocketUtility::send_command(const char* command){
websocket_outgoing_message o_msg;
std::string ws_response;
o_msg.set_utf8_message(command);
client->send(o_msg).then([](){
log("Message Sent!!!n");
});
client->receive().then([ws_response](websocket_incoming_message i_msg){ 
return i_msg.extract_string();
}).then([ws_response](std::string ws_body){ 
ws_response = ws_body;  
});
log("WS_RESPONSE:%s:n",ws_response.c_str());
return ws_response;
}

我试过
1.声明ws_response作为参考
2.在 lambda
中捕获ws_response作为参考 3.将ws_response声明为 cpprest json,并将响应分配为 json 字段(ws_response[U("output")] = json::value::string(ws_body.c_str(

)))没有运气。

我在C++方面没有太多编码经验,并且为此苦苦挣扎。

有人可以帮我如何在 lambda 之外捕获此响应,以便我可以将值返回给调用方法吗?

谢谢和问候,
斯瓦蒂·德赛

[ws_response](websocket_incoming_message i_msg){ return i_msg.extract_string(); }

上述 lambda 根本没有理由捕获ws_response,因为它不使用ws_response来做任何事情。

[ws_response](std::string ws_body){ ws_response = ws_body; }

上面的 lambda 需要通过引用捕获ws_response才能正确修改它。 lambda 当前编码的方式是,它按值捕获ws_response的副本,并且该副本const,因为 lambda 未声明为mutable。 这就是您收到编译器错误的原因 - 您尝试将ws_body分配给 lambda 本地的const std::string对象,而不是send_command()中声明的ws_response变量。 上面的 lambda大致相当于这个:

const std::string ws_response_copy = ws_response;
ws_response_copy = ws_body; // <-- ERROR

试试这个:

client->receive().then([](websocket_incoming_message i_msg){ 
return i_msg.extract_string();
}).then([&ws_response](std::string ws_body){ 
ws_response = ws_body;  
});

或者,extract_string()返回一个pplx::task<std::string>,它有一个get()方法来检索实际的std::string,等到它可用。所以以上可以简化为以下内容:

client->receive().then([&ws_response](websocket_incoming_message i_msg){ 
ws_response = i_msg.extract_string().get();
});

最新更新