new、delete 与内存
C++ 中 new 操作符内幕:new operator、operator new、placement new 1、new / delete 具体步骤 new 第一步:调用 operator new 函数分配一块足够大的,原始的,未命名的内存空间以便存储特定类型的对象 第二步:编译器运行相应的构造函数以构造对象,并为其传入初值 第三部:对象构造完成后,返回一个指向该对象的指针 delete 第一步:调用对象的析构函数 第二步:编译器调用 operator delete 函数释放内存空间 2、new/delete 与 malloc/free 的区别是什么? malloc/free 是 C 语言的标准库函数, new/delete 是 C++ 的运算符。它们都可用于申请动态内存和释放内存 malloc/free 不会去自动调用构造和析构函数,对于基本数据类型的对象而言,光用 malloc/free 无法满足动态对象的要求 malloc/free 需要指定分配内存的大小,而 new/delete 会自动计算所需内存大小 new 返回的是指定对象的指针,而 malloc 返回的是 void*,因此 malloc 的返回值一般都需要进行强制类型转换 operator new 重载: class Person{ public: Person(){ id = 0; score = 0; cout << "Person()" << endl; } Person(int id, int score):id(id),score(score){ cout << "Person(int, int)" << endl; } Person(const Person &p){ cout << "Person(const Person &p)" << endl; id = p....