【发布时间】: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