c++ - 取消分配从函数返回的动态数组

标签 c++

我有以下内容:

string *myFunction(void);

int main(void)
{
    string *newArrPtr = myFunction(void);

    //Do something with array

    //Deallocate memory here?
    //delete[] newArrPtr? 
    //newArrPtr = NULL? 

    return 0;
}

string *myFunction(void)
{
    string *oldArrPtr = new string[256];

    //Do something with array

    return oldArrPtr;

    //Deallocate memory here?
    //delete[] oldArrPtr? 
    //oldArrPtr = NULL? 
}

如您所见,我正在myFunction中创建一个新的动态分配的数组,但是现在我确定如何以及何时重新分配它。如果有人可以告诉我为什么?

最佳答案

but I'm now sure how and when to deallocate it again.



“如何”很容易:在处理数组时,只需使用deletedelete[]。 “何时”更有趣。您不能在delete[]中使用myFunction,因为您将在返回内存之前释放内存。旁注:在函数内部,如果您打算这样做,则在return语句之后不会执行任何代码。

因此,问题在于您的myFunction分配了内存,但不应释放它。当然,您可以在delete[]中使用myFunction之外的main。但这是一个不好的设计:某些函数返回一个指针。您获得了该指针,但是您无法知道谁负责释放。是你吗?是myFunction还是其他函数?还是指针指向某个根本不应该释放的内存?而且,您应该使用delete还是delete[]?该函数不会给您任何有关返回哪种指针的提示。这种设计迫使您要么完全了解myFunction的功能,要么正确记录其行为。此外,现在对myFunction的任何更改都很困难,这是一种易于引入向后不兼容(可能很难检测到)的更改的方法。仅仅是因为std::string*意味着太多事情。

C++通过引入std::unique_ptr<std::string>std::shared_ptr<std::string>解决了这个问题。处理单个对象时,请使用其中之一而不是原始指针。当处理数组时,我建议使用std::vector<std::string>。这样一来,情况就很清楚了,而且作为奖励,您根本不需要使用delete/delete[](尽管您可能不得不使用std::move来代替)。另一个好处(感谢@JorgeBellon)是,有了智能指针/ vector ,您就可以异常(exception)安全。

关于c++ - 取消分配从函数返回的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61651063/

相关文章:

c++ - 如何正确绑定(bind)2个纹理

c++ - boost Asio 套接字问题

c++ - 解引用指针给出一个地址

C++ Builder 2009 Float 与 Long Double

c++ - 为什么执行者不在 Concurrency TS 和 std::future 接口(interface)中了?

C++ WxWidgets : Redirecting Stdout to a wxTextCtrl across mulitple threads

c++ - 什么是 R 语言的快速免费矩阵/线性代数库?

c++ - 如果我想将 char 提升为 int,我应该使用 static_cast<int>(char variable) 还是 +(char variable)?为什么?

C++ 操作数到标准运算符的隐式转换

c++ - 为什么 const 变量不需要在模板类中初始化,直到实际使用该类?