我将这个函数作为我正在编写的类的一部分:
const char* sockets::TCPSocket::doRecv(int flags)
{
char* incomingDataBuffer = new char [this->bufferSize];
ssize_t bytesReceived = recv(this->filedes, incomingDataBuffer, this->bufferSize, flags);
// TODO set timeout - If no data arrives, the program will just wait here until some data arrives.
if (bytesReceived == 0 || bytesReceived == -1)
{
// TODO error handling
}
// TODO avoid memory leak
// delete[] incomingDataBuffer;
// incomingDataBuffer = 0;
return incomingDataBuffer;
}
如您所见,我的问题是我需要为传入的字符串动态分配缓冲区大小,并且我想将该值返回给用户。我不想留给用户释放内存,因为这看起来封装很差。
我的直觉是创建 incomingDataBuffer c 字符串的静态拷贝并将其返回给我的用户。然而,尽管进行了大量搜索,但我一直无法找到执行此操作的通用方法,这让我认为我可能只是采取了错误的方法。
显然我还有其他选择。
我可以使 incomingDataBuffer 成为一个类成员,然后在析构函数中处理它的删除,但这在某种程度上感觉不对,因为它没有其他理由成为一个类成员。
我想我可以遍历数组并将其转换为一个可以返回并转换为字符串的 vector 。但这同样感觉不太正确,因为 incomingDataBuffer 在某些情况下可能非常大,而且这种操作可能非常昂贵。
无论如何,我想这一定是标准方法的常见问题,那么正确的 c++ 方法是什么?
最佳答案
标准的 C++ 方法是使用 std::vector
:
std::vector<char> sockets::TCPSocket::doRecv(int flags)
{
std::vector<char> incomingDataBuffer(this->bufferSize);
ssize_t bytesReceived = recv(this->filedes,
&incomingDataBuffer[0], this->bufferSize, flags);
// TODO set timeout - If no data arrives,
// the program will just wait here until some data arrives.
if (bytesReceived == 0 || bytesReceived == -1)
{
// TODO error handling
}
// on success, do this so that call site knows how much data
// there actually is
incomingDataBuffer.resize(bytesReceived);
return incomingDataBuffer;
}
由于 vector
管理其内存,因此这里不存在内存泄漏问题。通过返回它,您只是将内存管理的责任转移给调用者——但调用者不必做任何特殊的事情。当 vector
超出范围时,内存会自动delete
d。
关于c++ - 如何删除分配的内存并仍然从方法返回它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30968318/