[英]Will this cause a memory leak in c++?
int* alloc()
{
int* tmp = new int;
return tmp;
}
int main()
{
int* ptr = alloc();
......
......
delete ptr;
return 0;
}
在這里我沒有釋放tmp但是ptr被明確釋放。 由於ptr和tmp指向相同的位置,tmp是否也會被釋放?
如果不是那么指針tmp會發生什么? 它會導致內存泄漏嗎?
不,這不會導致內存泄漏。 內存泄漏是已分配但未返回的緩沖區 (內存塊)(當它們將不再使用時)。 在你的alloc()
函數中, tmp
不是一個緩沖區......它是一個變量,在調用new
,它保存緩沖區的地址 。 您的函數返回此地址,在main()
,該地址存儲在ptr
變量中。 當你再打delete ptr
,你是釋放緩沖區 ptr
點,從而緩沖已被釋放,也沒有泄漏。
如果沒有拋出未捕獲的異常,您的程序將不會導致內存泄漏。
你可以做得更好,讓它像這樣100%防彈:
#include <memory>
std::unique_ptr<int> alloc()
{
std::unique_ptr<int> tmp { new int };
//... anything else you might want to do that might throw exceptions
return tmp;
}
int main()
{
std::unique_ptr<int> ptr = alloc();
// other stuff that may or may not throw exceptions
// even this will fail to cause a memory leak.
alloc();
alloc();
alloc();
auto another = alloc();
// note that delete is unnecessary because of the wonderful magic of RAII
return 0;
}
盡早養成這個習慣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.