如何在创建函数返回的范围的末尾解除分配已分配的内存?

时间:2014-02-26 12:18:46

标签: c++ arrays allocation

我在下面的代码中用注释说明了问题:

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?
}

也许我需要制作一些小型垃圾收集系统?

2 个答案:

答案 0 :(得分:3)

为什么要退回char *?您可以返回std::string而不是管理自己的记忆。

或者,当使用其他类型的数组std::vector将为您管理存储时

您在代码中隐藏评论的位置可能会解释您的混淆来源 - //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?

您的陈述不正确。在评估整个表达式后,临时将死亡 让我们假设存在这些函数:

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中的临时字符数组不会被不必要地复制

答案 1 :(得分:0)

使用std::string返回基于char的字符串。

它为您处理内存分配和释放。