malloc/free 和 new/delete的区别

发布时间 2023-09-17 23:05:50作者: 邹木木
class Test
{
public:
	char *a;
	Test() {
		this->a = (char *)malloc(10);//this->a表示对象自身的成员a
		strcpy_s(this->a, 10, "hello");
		printf("Test init\n");
	}
	~Test() {
		free(this->a);
		printf("Test deInit\n");
	}
};

int main()
{

	char *a = (char *)malloc(10);  //malloc不会做初始化
	Test *t = new Test; //new会自动调用构造函数进行初始化
	printf("a = %s\n", a);
	printf("t->a = %s\n", t->a);
	
	delete t;//new出来的对象需要手动delete,不会自动释放;同时delete会自动调用析构函数
	t = new Test;//new一个新对象
	return 0;
}