delete 对象地址;
delete 首先调用待清除对象的析构函数,然后释放内存
如果delete一个void指针,唯一发生的事情就是释放了内存。因为通过void指针,无法知道对象的类型,就无法调用其析构函数。
delete []books;
[]告诉编译器,books实际上是一个对象数组的起始地址。该代码的任务是,把数组创建时存放在某处的数组元素个数取回,并为数组的所有对象调用析构函数。
1 测试程序deleteTest.cpp
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 class Book 7 { 8 string name; 9 string author; 10 double price; 11 12 public: 13 Book() : name("null"), author("null"), price(0) 14 { 15 cout << "invoke constructor Book() " << endl; 16 } 17 Book(string name, string author, double price) : name(name), author(author), price(price) 18 { 19 cout << "invoke constructor Book(string " << name << ", string " << author << ", double "<< price << ") " << endl; 20 } 21 22 //复制构造函数 23 Book(const Book& b) : name(b.name), author(b.author), price(b.price) 24 { 25 cout << "Book::Book(const Book& b)" << endl; 26 } 27 28 ~Book() 29 { 30 cout << "~Book()" << endl; 31 cout << "free book: '" << name << "'" << endl; 32 } 33 34 friend ostream& operator<<(ostream& os, const Book& b) 35 { 36 return os << "BookName: " << b.name << ", BookAuthor: " << b.author 37 << ", BookPrice: " << b.price; 38 } 39 40 //重载赋值运算符 41 Book& operator=(const Book& b) 42 { 43 cout << "Book::operator=(const Book&)" << endl; 44 name = b.name; 45 author = b.author; 46 price = b.price; 47 48 return *this; 49 } 50 }; 51 52 53 54 int main() 55 { 56 //数组book里放的是Book类型的指针 -- 使用new在堆上创建对象数组 57 //在堆上为‘5个Book对象’分配了内存,并为这5个Book对象调用了构造函数 58 Book* books = new Book[5]; 59 60 Book* b1 = new Book("算法精解", "Kyle Loudon", 56.2); 61 Book* b2 = new Book("Qt程序设计", "Pulat", 10.2); 62 63 books[0] = *b1; // 64 books[1] = *b2; 65 66 cout << "---- delete b1 ----" << endl; 67 delete b1; 68 cout << "---- delete b2 ----" << endl; 69 delete b2; 70 71 cout << "---- delete []books ----" << endl; 72 delete []books; 73 74 return 0; 75 };
运行结果:
2 对象数组
Book* books = new Book[5];
使用new在堆上创建了一个包含5个Book对象的数组,books是该数组的起始地址(首地址、第一个元素的地址)
books是一个指向Book对象的指针变量,与Book* bk1 = new Book;创建一个Book对象的语法形式是一样的;但Book* books = new Book[5];编译器会记住books指向的Book对象后面还跟4个Book对象。