首页 > C++编程 > delete Operator in C++

delete Operator in C++

Deallocates a block of memory.

[::] delete cast-expression
[::] delete [ ] cast-expression

Remarks

The cast-expression argument must be a pointer to a block of memory previously allocated for an object created with the new operator. The delete operator has a result of type void and therefore does not return a value. For example:

CopyCDialog* MyDialog = new CDialog;
// use MyDialog
delete MyDialog;

Using delete on a pointer to an object not allocated with new gives unpredictable results. You can, however, use delete on a pointer with the value 0. This provision means that, when new returns 0 on failure, deleting the result of a failed new operation is harmless. See The new and delete Operators for more information.

The new and delete operators can also be used for built-in types, including arrays. If pointer refers to an array, place empty brackets before pointer:

Copyint* set = new int[100];
//use set[]
delete [] set;

Using the delete operator on an object deallocates its memory. A program that dereferences a pointer after the object is deleted can have unpredictable results or crash.

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor).

If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

Example

// operator delete[] example
#include <iostream>
#include <new>
using namespace std;

struct myclass
{
	myclass()
	{
		cout <<"myclass constructed\n";
	}
	~myclass() 
	{
		cout <<"myclass destroyed\n";
	}
};

int main ()
{
	myclass * pt;

	pt = new myclass[3];
	delete[] pt;

	return 0;
}

 Result of the code:

myclass constructed
myclass constructed
myclass constructed
myclass destroyed
myclass destroyed
myclass destroyed

Reference

http://msdn.microsoft.com/en-us/library/h6227113.aspx
http://www.cplusplus.com/reference/std/new/operator%20delete%5B%5D/


觉得文章还不错?点击此处对作者进行打赏!


本文地址: 程序人生 >> delete Operator in C++
作者:代码疯子(Wins0n) 本站内容如无声明均属原创,转载请保留作者信息与原文链接,谢谢!


更多



分类: C++编程 标签: , ,
  1. 本文目前尚无任何评论.
  1. 2010年10月29日04:17 | #1