Phi*_*Elm 4 c++ pointers arguments memory-management
我一直在研究C++如何处理作为参数传递的指针,但到目前为止我还没有找到一个可靠的"是/否"答案.
我是否需要在它们上调用delete/free,或者C++是否足够聪明以清除它们自己的?
我从来没有见过有人在传递指针上调用delete,所以我假设你不需要,但我想知道是否有人知道实际需要它时的任何情况.
谢谢!
用于作为参数传递的指针的存储将被清除.但他们指出的记忆不会被清理干净.
所以,例如:
void foo(int *p) // p is a copy here
{
return;
// The memory used to hold p is cleared up,
// but not the memory used to hold *p
}
int main()
{
int *p = new int;
foo(p); // A copy of p is passed to the function (but not a copy of *p)
}
Run Code Online (Sandbox Code Playgroud)
你会经常听到人们谈论"在堆上"和"在堆栈上".* 局部变量(例如参数)存储在堆栈中,自动清理.使用new(或malloc)分配的数据存储在堆上,不会自动清理.