new 和 deletec++ 的 new 和 delete 与 c的 malloc 和 free 区别之一是: 调用 new 和 delete 时会调用类的构造函数和析构函数 上代码 #include <iostream> using namespace std; class student { private: int age; public: student(int a); ~student(); }; //构造函数 student::student(int a) { age = a; cout << "student" << endl; } //析构函数 student::~student() { cout << "~student" << endl; } int main() { student *a = new student(2); //delete a; return 0; } 输出 student 因为没有调用 delete a,所以只有构造函数被调用了。 加上 delete a 输出 student
~student
可知,在调用 delete 时 才会调用类的析构函数 如果不调用delete *a 上的空间就会泄漏
|
|