c++ new和malloc的完全等价写法*

#include <stdlib.h>

#include <iostream>
#include <string>
using namespace std;
class Person {
   public:
    Person() {
        id = 0;
        name = nullptr;
        cout << "constructor" << endl;
    };

   public:
    int id = 0;
    // 如果不加const会有编译告警
    const char* name = "qiumc";
};

int main() {
    // 如下两种方式等价,分别是C++和C语法,它们都不会调用构造函数
    Person* personPtr1 = static_cast<Person*>(::operator new(10 * sizeof(Person)));
    Person* personPtr2 = (Person*)malloc(10 * sizeof(Person));

    // 这种方式会调用2次默认构造函数
    auto x = new Person[2];

    return 0;
}
posted @ 2021-10-25 21:14  邱明成  阅读(199)  评论(0编辑  收藏  举报