cpp_go_hdc4

heap objects 的生命期

class Complex {
      ... };
...
{
     
	Complex* p = new Complex;
	...
	delete p;
}

p 所指的便是heap object, 其生命在它被deleted之际结束

class Complex {
      ... };
...
{
     
	Complex* p = new Complex;
}

以上出现内存疏漏(memory leak),
因为当作用域结束,p所指的heap object仍然存在,但指针p的生命却结束了,作用域之外再也看不到p(也就没机会delete p)

new:先分配memory,再调用ctor

Complex* pc = new Complex(1,2);

编译器转化为

Complex *pc;
void* mem = operator new(sizeof(Complex));	//1分配内存
pc = static_cast<Complex*>(mem);	//2转型
pc ->Complex::Complex(1,2);	//3构造函数

1分配内存 ->其内部调用malloc(n)
3构造函数 -> Complex::Complex(pc,1,2)

delete: 先调用dtor,再释放memory

String* ps = new String("Hello");
...
delete ps;

编译器转化为:

String::~String(ps);	//析构函数
operator delete(ps);	//释放内存

动态分配所得的内存块(memory block),in VC

cpp_go_hdc4_第1张图片
动态分配所得的array
cpp_go_hdc4_第2张图片

array new 一定要搭配array delete

String* p = new String[3];
...
delete[] p;		//唤起3次dtor
String* p = new String[3];
...
delete p;	//唤起1次dtor

你可能感兴趣的:(cpp_go_hdc4)