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)
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)
String* ps = new String("Hello");
...
delete ps;
编译器转化为:
String::~String(ps); //析构函数
operator delete(ps); //释放内存
动态分配所得的内存块(memory block),in VC
String* p = new String[3];
...
delete[] p; //唤起3次dtor
String* p = new String[3];
...
delete p; //唤起1次dtor