// ============================================================================ // p1c04_03_09 — 4.3.9.3 new operator // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; // --- 原文片段 [58954451:8] 4.3.9.3 new operator --- // 原文为伪代码对照,演示 new 与 malloc 的等价关系: // Person* person = new Person; // 相当于: // Person* person = (Person*)malloc(sizeof(Person)); // if(person == NULL){ return 0; } // person->Init(); // 构造函数 // 下面给出可编译的对照程序: #include #include #include class Person { public: Person() { std::cout << "构造函数!" << std::endl; } void Init() { std::cout << "Init" << std::endl; } }; int main() { Person* person = new Person; // C++: new 自动调用构造函数 Person* p2 = (Person*)malloc(sizeof(Person)); if (p2) { new (p2) Person(); } // 对齐 new 的行为(placement new) delete person; if (p2) { p2->~Person(); free(p2); } return 0; } // --- main ---