C++入门--new与delete
举个🌰
#include <stdlib.h> #include <iostream> #include <string> using namespace std; class CStudent { public: CStudent() { cout << "CStudent()\r\n"; } ~CStudent() { cout << "~CStudent()\r\n"; } private: int mStuID; }; int main(int argc, char const* argv[]) { //在堆上分配对象 CStudent* pStu = (CStudent*)malloc(sizeof(CStudent)); free(pStu); return 0; }
栈对象 / 全局对象 / 堆对象
如上使用malloc在堆上分配对象,执行后并没有调用构造域析构函数
C语言上的malloc域free不会主动调用对象的构造域析构,所以C++就有了new与delete运算符
#include <stdlib.h> #include <iostream> #include <string> using namespace std; class CStudent { public: CStudent() { cout << "CStudent()\r\n"; } ~CStudent() { cout << "~CStudent()\r\n"; } private: int mStuID; }; int main(int argc, char const* argv[]) { // CStudent* pStu = (CStudent*)malloc(sizeof(CStudent)); // free(pStu); CStudent* pStu = new CStudent; if (pStu != nullptr) { delete pStu; } return 0; }
out:
C语言中malloc与free仅仅只是分配释放空间,到了C++中,满足不了需求 new //分配空间,调用构造函数 delete //调用析构函数,释放空间 //对于基本数据类型而言,new与delete仅仅分配了内存空间
同一个类的成员函数地址是一样的,表示同一个类的对象的成员函数是共用的;
(1)数据是独立的
(2)成员函数是共用的
this指针
成员函数调用时会偷偷的传递this指针,通过寄存器ecx传递,这种传递方式称为thiscall
通常情况,构造域析构都是公有的;