array new /delete

使用构造函数,构造函数连续构造:

#include <iostream>
#include <complex>
#include "class_a.h"
using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define size 3
int main(int argc, char** argv) {
	//complex* pa = new complex[3];
	//内存泄漏就是只是释放了一块儿内存地址,当然删除一次和删除三次其实效果是一样的。
	//使用array new 就要使用array delete
	
	A* buf = new A[size];//调用默认构造函数 构造是由上向下的 
	A* tmp = buf;
	
	cout<<"buf="<<buf<<" tmp="<<tmp<<endl;//证明buf和temp的内存地址是完全一样的 
	
	for(int i=0;i<size;i++)
	{
		new(tmp++)A(i);//ctor3次调用构造函数 (会直接将上面默认构造的元素替代) 
	}
	
	
	
	cout<<"buf="<<buf<<" tmp="<<tmp<<endl;
	
	delete[] buf;//析构是由下向上的 
	
	
	return 0;
}

  上述代码说明,array new和array delete,是一对必须一起使用,否则会造成内存泄露。上述代码是整型变量,不存在析构函数,也就不存在内存泄漏,所以即使不使用析构函数也影响不大。

猜你喜欢

转载自www.cnblogs.com/yjds/p/8948526.html