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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM