【问题标题】:Passing std::string_view to API execting const std::string&将 std::string_view 传递给执行 const std::string& 的 API
【发布时间】:2019-03-25 07:00:52
【问题描述】:

我正在使用 Socket.IO 库来创建客户端。在发送消息时,我必须将我的消息(数据)作为sio::message::list(msg)

void Socket_IO::send_message(std::string_view msg)      //Gives Error
//void Socket_IO::send_message(const std::string &msg)  //Works
{
    this->client.socket()->emit(Socket_IO::general_message, sio::message::list(msg), [&](sio::message::list const& msg) {
    });
}

class sio::message::list 有一个构造函数

list(const string& text)
{
    m_vector.push_back(string_message::create(text));
}

但没有 std::string_view 构造函数

错误:

'<function-style-cast>': cannot convert from 'std::string_view' to 'sio::message::list'

我想知道他们是否可以通过 std::string_view 为 API 期待 const std::string&

我不能使用 c_str() 函数,因为字符串可能包含可能包含空字符 (0x00) 的二进制数据。

我正在考虑创建一个字符串对象sio::message::list(std::string str(msg)),但想询问它是否会破坏使用 std::string_view 的目的。

【问题讨论】:

  • 使用 string_view 没有任何意义。 string_view 旨在处理来自某些第三方字符串源的一系列不可变字符。它不能替代 api 中的所有字符串。理想情况下,它不应该被纳入标准。

标签: c++ std c++17 stdstring


【解决方案1】:

你可以选择:

this-&gt;client.socket()-&gt;emit(Socket_IO::general_message, sio::message::list(std::string(msg)), ...

这使工作完成。它将初始化临时字符串对象并将其传递给列表构造函数。

【讨论】:

  • 正如我帖子最后一行中提到的,我想知道使用 std::string 构造会导致性能问题。
  • 每一个新的对象构造都会,但除非你是为超关键的时间或内存受限的环境进行开发,否则它没有任何区别,它可以解决你的问题。
猜你喜欢
  • 2021-12-29
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 2017-02-28
  • 2012-12-27
  • 1970-01-01
  • 2015-09-26
  • 2020-11-04
相关资源
最近更新 更多