c++ - 如何在创建函数返回的范围末尾释放分配的内存?

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

也许我需要做一些小型的迷你垃圾收集系统?

最佳答案

为什么返回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/

相关文章:

c++ - Direct2D:将文本转换为路径

c++ - Windows默默捕捉到的异常,如何手动处理?

ios - 如何在 Swift 中获取 NSMutableArray 中元素的索引?

arrays - 无法使用 Mongoose 将嵌套 JSON 数组存储到 MongoDB

compilation - 与默认的 4KB 相比,16KB 或 32KB 的 NTFS 分配 block 是否会使编译时间更快?

java - get/setPreferredSize 无需每次都分配 Dimension 对象

c++ - Lambda 函数无法在 Visual Studio 2010 中编译

c++ - 从原始内存位置 memcpy 到 vector<wchar_t>

c - 在 C 中使用 strstr 方法与两个数组?

c++ - 堆栈与缓存友好分配器