c++中new和delete总结

1、先说说 new delete 和 malloc free的区别
    1.1 malloc free 是C语言的标准库函数。
    
    1.2 new delete 操作符,类似于sizeof    ,因此执行效率高。
    
    1.3 new一个对象的同时可以进行初始化。malloc则不能。
    
    1.4 new一个类的时候会调用构造函数,delete时会调用析构函数,而malloc free 不会。
    


2、一个简单的类:

class Test
{
public:
	Test()
	{
		m_a = 0;
		m_b = 0;
		cout << "0,0 构造" << endl;
	}
	Test(int a, int b)
	{
		m_a = a;
		m_b = b;
		cout << "a = " << m_a << ", b = " << m_b << "构造 " << endl;
	}

	void setA(int a)
	{
		m_a = a;
	}
	void setB(int b)
	{
		m_b = b;
	}

	void printT()
	{
		cout << "a = " << m_a << ", b = " << m_b << endl;
	}

	~Test()
	{
		cout << "a = " << m_a << ", b = " << m_b << "析构 " << endl;
	}
private:
	int m_a;
	int m_b;
};

3、c语言实现动态分配

void test1()
{
	int *p = (int*)malloc(sizeof(int));
	*p = 10;
	cout << *p << endl;
	if (p != NULL) {
		free(p);
		//delete p; //delete 可以释放malloc的开辟的内存
	}

	int *array_p = (int*)malloc(sizeof(int)* 10);
	for (int i = 0; i < 10; i++) {
		array_p[i] = i + 10;
	}

	for (int i = 0; i < 10; i++) {
		cout << array_p[i] << endl;
	}

	if (array_p != NULL) {
		free(array_p);
	}


	cout << " --------  " << endl;

	Test *tp = (Test*)malloc(sizeof(Test)); //不会调用对象的构造函数
	tp->setA(10);
	tp->setB(20); //malloc出来的对象指针,只能够通过成员函数来进行初始化
	tp->printT();

	if (tp != NULL) {
		free(tp); //不会调用对象的析构
	}
}

4、c++实现动态分配

void test2()
{
	//new 能够完成所有malloc的需求
	int *p = new int; //在堆上动态开辟4个字节
	*p = 10;
	cout << *p << endl;

	if (p != NULL) {
		//delete p; //delete 一个变量
		free(p); //用new开辟的内存, free也能够释放。
	}

	cout << "-----" << endl;

	int *array_p = new int[10];
	for (int i = 0; i < 10; i++) {
		array_p[i] = i + 10;
	}
	for (int i = 0; i < 10; i++) {
		cout << array_p[i] << endl;
	}

	if (array_p != NULL) {
		delete[]   array_p; //delete 一个数组
	}


	cout << "-------" << endl;
	//Test *tp = new Test(10, 20);//调用了有参数的构造函数 
	Test *tp = new Test;//调用了无参构造函数
	tp->printT();
	if (tp != NULL) {
		delete tp; //delete在释放一个对象指针的时候,会调用对象析构函数
	}
}

猜你喜欢

转载自blog.csdn.net/amumu_123/article/details/81408479