目录
1.简介
2.底层
1.简介
new是升级版的malloc,它会先开空间再去调用构造函数。
delete是升级版的free,它会先调用析构函数再free掉空间。
class A
{
public:
A(int a1=0, int b1=0)
{
a = a1;
b = b1;
}
private:
int a;
int b;
};
int main()
{
//new会先开空间再调用构造函数
A* p1 = new A;
A* p2 = new A(1, 1);
//new多个对象并调用构造函数初始化
A* p3 = new A[3];
//隐式类型转换:先构造出临时对象再调用拷贝构造
A* p4 = new A[3]{ {1,2},{2,3},{3,5} };
//运用匿名对象初始化,先是构造匿名对象,再拷贝构造(编译器会优化成一次构造)
A* p5 = new A[3]{ A(1,1),A(2,2),A(3,3) };
//delete会先调用析构函数,再free掉空间
delete p1;
delete p2;
delete [] p3;
delete [] p4;
delete [] p5;
return 0;
}
2.底层
//模拟底层
//先是开空间,这里和malloc没区别
A* p6 = (A*)operator new(sizeof(A));
//显式调用构造函数
new(p6)A(1, 2);
//显式调用析构函数
p6->~A();
//释放空间
operator delete (p6);