我的第一个问题是,当函数结束时,函数中由 new 分配的内存是否会自动删除(释放)。
int* foo()
{
int *a = new int; //memory allocated for an int
*a = 3;
return (a);
}//function ends -- is memory for integer still allocated.
如果内存在函数结束后自动取消分配,那么我的下一个代码不应该给出一些与访问不属于我的内存相关的错误。
int main()
{
int *x = foo();
cout<<*x;
}
最佳答案
不,当然不是。每个 new
都必须与 delete
平衡。 (并且,为了避免任何 future 的疑问,任何 new[]
都必须与 delete[]
保持平衡)。
C++ 中有一些结构可以在容器对象超出范围后有效释放内存。看看 std::shared_ptr
和 std::unique_ptr
。
关于c++ - new 的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22911125/