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

// 创建时
int *ptr1 = new int (5); // use direct initialization
int *ptr2 = new int { 6 }; // use uniform initialization

// 释放时 (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.
*/
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容