簡體   English   中英

我需要在這里調用析構函數嗎?

[英]Do I need to call de destructor here?

Ok, so lets say I have a heap allocated object... if I use placement new and create a new object in the memory location where the other used to 'live', will that cause a memory leak? 或者,這就是我的想法,它會覆蓋它嗎?

Object* ptr = new Object(1);
new(ptr) Object(2);

還是我需要顯式調用析構函數,因為它不會被覆蓋?

Object* ptr = new Object(1);
delete ptr;
new(ptr) Object(2);

兩種選擇都是錯誤的。

調用 new 運算符會導致兩件事:分配 memory 和調用構造函數。 Placement new 僅在 memory 的預分配塊上調用構造函數。 另一方面,調用 delete 會導致調用析構函數並釋放 memory。 在放置 new 之后你必須做的是顯式調用析構函數。 但是在 C++ 中,最好的選擇總是使用 RAII 模式。

使用placement new,您需要顯式調用析構函數,這與調用delete不同。

就像是:

typename std::aligned_storage<sizeof(Object), alignof(Object)>::type buffer;

Object* ptr = new (&buffer) Object(1);
// ...
ptr->~Object(); // Destructor call.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM