我在下面的代码中用注释说明了这个问题:
class MyClass //Some string-like class that encapsulates a dynamic char array.
{
public:
MyClass(unsigned int size)
{
data = new char[size];
}
char* GetCharArray() //In places where passing the raw array is needed, I call this method, but I want to create a separate char array and not touch the original one.
{
char* temporary = new char[size + someNumber];
for(int i = 0; i < size; i++)
{
temporary[i] = data[i];
}
DoSomeOperationForRemainingCharacters(temporary);
return(temporary);
}
private:
char* data;
unsigned int size;
};
void SomeFunc(char* c);
int main()
{
MyClass string(50):
SomeFunc(string.GetCharArray()); //A new char array is allocated here, but it is
// never deleted. If I return a templated pointer wrapper that wraps the array
// and deletes it in the destructor, the wrapper dies at the end of
// GetCharArray(), so by the time it's passed to SomeFunc(), the char array is
// already deleted. What else can I do?
}
也许我需要做一些小型的迷你垃圾收集系统?
最佳答案
为什么返回char*?您可以返回 std::string
而不是它将管理自己的内存。
或者当使用其他类型的数组时,std::vector
将为您管理存储
您在代码中隐藏了一条注释,这可能会解释您的困惑的根源 - //此处分配了一个新的 char 数组,但它永远不会被删除。如果我返回一个包装数组并在析构函数中将其删除的模板化指针包装器,包装器会在 GetCharArray() 结束时终止,因此在它传递给 SomeFunc() 时,char 数组已经被删除。我还能做什么?
您的说法不正确。整个表达式被求值后,临时对象将消亡 让我们假设这些函数存在:
void SomeFunc(const char* input); //old style C function that expects a raw char pointer
//creates a temporary string and returns it
std:string GetString() {
std::string temp = "whatever";
... lots of manipulation ...
return temp;
}
然后你计算这个表达式:
SomeFunc(GetString().c_str());
C++ 标准保证 GetString() 返回的临时字符串只有在整个表达式被计算时才会被释放。
使用 c++11 move-ctor std::string
中的临时 char 数组将不会被不必要地复制
关于c++ - 如何在创建函数返回的范围末尾释放分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22041152/