- When you delete a class object, the destructor is called for the class.
- If you delete an array of class objects, without using delete [], the destructor may only be called once, instead of once for each array object.
Example 4-15 - delete and destructors
1 // File: eTest4-15.cpp - delete or delete []
2
3 #include <iostream>
4 using namespace std;
5
6 class Test
7 {
8 int n;
9 public:
10 Test() { n = 0; cout << "Test constructor called\n"; }
11 ~Test() { cout << "Test destructor called\n"; }
12 };
13
14 int main(void)
15 {
16 Test* ptrTest;
17
18 cout << "allocate space for 1 Test\n";
19 ptrTest = new Test;
20 delete ptrTest;
21
22 cout << "allocate space for 3 Tests\n";
23 ptrTest = new Test[3];
24 delete ptrTest;
25 // MS Visual C++ 2008 calls the destructor once, then errors
26 // Digital Mars C++ Compiler (ver 8.42) calls the destructor once
27 // gnu compiler (ver 4.3.1) calls destructor once, then crashes
28 return 0;
29 }****** Output ******
allocate space for 1 X
X constructor called
X destructor called
allocate space for 3 Xs
X constructor called
X constructor called
X constructor called
X destructor called
What is the problem here?
沒有留言:
張貼留言