new出来对象会调用对象的构造函数,但是malloc出来的对象是没有调用构造函数的,因此下面使用malloc初始化的对象私有变量是没有经过构造函数初始化的但是通过new出来的对象,对象已经经过构造函数的初始化。
//
// Created by andrew on 2021/3/8.
//
#include <iostream>
#include <string>
using namespace std;
class MallocClass {
private:
string _valor;
public:
MallocClass() {
_valor = "Malloc_test";
}
const string &get() const {return _valor;}
void set(const string &valor) { this->_valor = valor;}
};
int main(int argc, char ** argv)
{
auto * mallocClass = (MallocClass*)malloc(sizeof(MallocClass));
// 输出为空,说明malloc申请的对象是没有调用构造函数
cout << mallocClass->get() << endl;
mallocClass->set("set");
free(mallocClass);
cout << "class malloc end ==============" << endl;
auto *mallocClass1 = new MallocClass;
cout << mallocClass1->get() << endl;
return 0;
}
可以看出new出来的对象私有变量是经过初始化的,malloc
输出结果:
/work/achou-leetcode/cmake-build-debug/test
class malloc end ==============
Malloc_test
Process finished with exit code 0