原完整教程链接: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.
*/
网友评论