使用 delete
delete 運算子有兩種語法變化:一種用於單一物件,另一種用於物件陣列。 下列程式碼片段示範兩者不同之處:
// expre_Using_delete.cpp
struct UDType
{
};
int main()
{
// Allocate a user-defined object, UDObject, and an object
// of type double on the free store using the
// new operator.
UDType *UDObject = new UDType;
double *dObject = new double;
// Delete the two objects.
delete UDObject;
delete dObject;
// Allocate an array of user-defined objects on the
// free store using the new operator.
UDType (*UDArr)[7] = new UDType[5][7];
// Use the array syntax to delete the array of objects.
delete [] UDArr;
}
下列兩種情況會產生未定義的結果:對物件使用陣列形式的刪除 (delete [ ]),以及對陣列使用非陣列形式的刪除。