我有以下内容:
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.
“如何”很容易:在处理数组时,只需使用
delete
或delete[]
。 “何时”更有趣。您不能在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/