6.9 Dynamic memory allocation with new and delete

原完整教程鏈接:6.9 Dynamic memory allocation with new and delete

1.
// Basic operations of dynamic memory allocation

// 創(chuàng)建時(shí)
int *ptr1 = new int (5); // use direct initialization
int *ptr2 = new int { 6 }; // use uniform initialization

// 釋放時(shí) (assume ptr has previously been allocated with operator new)
delete ptr; // return the memory pointed to by ptr to the operating system
ptr = 0; // set ptr to be a null pointer (use nullptr instead of 0 in C++11)

2.
/*
   A pointer that is pointing to deallocated memory is called a 
   dangling pointer. Dereferencing or deleting a dangling pointer will 
   lead to undefined behavior.
*/
int main()
{
    int *ptr = new int; // dynamically allocate an integer
    int *otherPtr = ptr; // otherPtr is now pointed at that same memory location
 
    delete ptr; // return the memory to the operating system. 
                // ptr and otherPtr are now dangling pointers.
    ptr = 0; // ptr is now a nullptr
 
    // however, otherPtr is still a dangling pointer!
 
    return 0;
}

3.
// Deleting a null pointer has no effect. Thus, there is no need for the 
// following:
if (ptr)
    delete ptr;

// Instead, you can just write:
delete ptr;
// If ptr is non-null, the dynamically allocated variable will be deleted. 
// If it is null, nothing will happen.

4.
/*
   Memory leak:
   Memory leaks happen when your program loses the address of 
   some bit of dynamically allocated memory before giving it back to 
   the operating system. When this happens, your program can’t 
   delete the dynamically allocated memory, because it no longer 
   knows where it is. The operating system also can’t use this 
   memory, because that memory is considered to be still in use by 
   your program.
*/
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容