【问题标题】:Array of char using unique_ptr in this specific case在这种特定情况下使用 unique_ptr 的 char 数组
【发布时间】:2017-04-27 19:23:38
【问题描述】:

我目前正在使用 C++ 中的套接字开发一个小型服务器。

我有一个发送字符串的函数:

void SocketServer::SendData(int id_client, const std::string &str)
{
  int size = str.size();
  send(id_client, &size, 4, 0);
  send(id_client, str.c_str(), str.size(), 0);
}

首先,我发送 4 个字节,对应于我要发送的字符串的长度。

然后,我有一个接收字符串的函数:

int SocketServer::ReceiveData(int id_client)
{
  char  buffer[1024]; // <<< this line, bad idea, I want to use unique_ptr
  int size = 0;
  int ret = 0;

  ret = recv(id_client, &size, 4, 0);  //<<< Now I know the length of the string I will get

  if (ret >= 0)
  {
    ret = recv(id_client, buffer, size, 0);
    if (ret >= 0)
    {
      buffer[ret] = '\0';
      std::cout << "Received: " << buffer << std::endl;
    }
  }
  return (ret);
}

我不想使用固定缓冲区,我想使用 unique_ptr(因为这是尊重 RAII 的好方法)

我该怎么做?

非常感谢

【问题讨论】:

    标签: c++ c++11 unique-ptr


    【解决方案1】:

    您可以改用std::string

    std::string buffer;
    int size = 0;                                                                                          
    int ret = 0;                                                                                           
    
    ret = recv(id_client, &size, 4, 0);
    buffer.resize(size);
    
    //later..
    recv(id_client, &buffer[0], size, 0);             
    

    buffer 现在将包含接收到的数据和正确的大小。它也会因为 RAII 而为你销毁。

    【讨论】:

    • 您好,感谢您的回答,它就像一个魅力!不知道std::string也被认为是char*,谢谢!
    • 顺便说一句,你对stackoverflow来说太快了,我必须等待5分钟才能批准你的回答,谢谢!
    • @void &amp;string[0]only guaranteed to work since C++11 标准。另请参阅this answer
    • @zett42 OP 询问了unique_ptr 的解决方案,这也是最低限度的 C++11。
    • 很公平。我建议添加适当的标签。
    猜你喜欢
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多