在此特定情况下使用 unique_ptr 的字符数组
Array of char using unique_ptr in this specific case
我目前正在使用 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] = '[=12=]';
std::cout << "Received: " << buffer << std::endl;
}
}
return (ret);
}
我不想使用固定缓冲区,我想使用 unique_ptr(因为这是尊重 RAII 的好方法)
我该怎么做?
非常感谢
您可以只使用 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 而为你销毁。
我目前正在使用 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] = '[=12=]';
std::cout << "Received: " << buffer << std::endl;
}
}
return (ret);
}
我不想使用固定缓冲区,我想使用 unique_ptr(因为这是尊重 RAII 的好方法)
我该怎么做?
非常感谢
您可以只使用 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 而为你销毁。