In C ++ new / delete / malloc / free knowledge summary

note

  • new will call the constructor, malloc does not call constructors
  • delete calls the destructor, free does not call the destructor
  • just released a free memory space object is located, if the member variable self-defined types in the management of the resource, the resource will not be released, it will have a memory leak (because the destructor is not called)
  • delete [] and an error as long as no new [] matches will be used to run the custom type
  • malloc call the constructor does not apply for the space, the application is the same size as a target memory space, the memory space can not speak the block as an object
  • When using malloc delete released objects created, it will call the destructor to clean up object resources, if from member variables defined types in the management of the resources will be an error, because there is no malloc call the constructor, not to the variable resource management application memory, of course, be wrong at this time to free up space
  • Use _CrtDumpMemoryLeaks () function to detect whether a memory leak, the leaked a few bytes and

The following code can fully understand these points

// new会调用构造函数
// free不会调用析构函数--对象中的资源不会被销毁
void Test2()
{
	Test* p3 = new Test;
	Test* p4 = new Test;
	free(p3);     //free只是释放了对象所在的内存空间,如果自定义类型中的成员变量
	              //管理了资源,将无法释放该资源,会产生内存泄露(因为没有调用析构函数)
	delete[] p4;  //delete[] 在自定义类型中只要没有和new[]匹配使用就会运行时出错

	// malloc申请空间时不会调用构造函数--申请的是与对象大小相同的一块内存空间
	// 不能讲该块内存空间看成是一个对象

	Test* p1 = (Test*)malloc(sizeof(Test));
	Test* p2 = (Test*)malloc(sizeof(Test));
	delete p1;    // 会调用析构函数清理对象中的资源,如果自定义类型中的成员变量
	              //管理了资源,将会报错,因为malloc没有调用构造函数,没有给管
				  //理资源的变量申请内存,此时释放空间当然会出错。
	delete[] p2;  //delete[] 在自定义类型中只要没有和new[]匹配使用就会运行时出错

	Test* p5 = new Test[10];
	Test* p6 = new Test[10];
	free(p5);      //free释放new[]创建的运行时会出错
	delete p6;     //delete释放new[]创建的运行时会出错
	_CrtDumpMemoryLeaks();
}
Published 157 original articles · won praise 53 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_42837885/article/details/101127056