malloc
和 new
都是用于在 C 和 C++ 中分配内存的操作,但它们之间有几个主要的区别:
1. 语言层面的区别
malloc
是 C 语言标准库中的一个函数,也可以在 C++ 中使用。new
是 C++ 语言中的一个操作符,它不仅分配内存,还会调用对象的构造函数。
2. 构造函数和析构函数
malloc
仅仅分配内存,不调用构造函数,因此不会初始化对象。new
分配内存的同时会调用对象的构造函数,初始化对象。
4. 返回类型
malloc
返回一个void*
类型的指针,需要显式地转换成目标类型的指针。new
返回的指针类型与所分配对象的类型相匹配,无需类型转换。
6. 内存释放
- 使用
malloc
分配的内存应该使用free
来释放。 - 使用
new
分配的内存应该使用delete
来释放,这会调用对象的析构函数。
8. 数组分配
malloc
分配数组时,你需要计算整个数组的大小。new[]
操作符可以直接分配数组,并且会为数组中的每个元素调用构造函数。
写以下代码测试时遇到了类成员与对象和python搞混的情况,在注释中梳理了一下。
#include<iostream>
#define ARRAY_SIZE 10
using namespace std;
//定义类Test
class Test{
public:
//定义构造函数与析构函数,注意C++默认类成员熟悉为private,需要显式定义public
Test(string name);
~Test();
//定义类成员属性,注意c++用static 定义类成员属性,用this指针访问
//而python用self直接使用并声明类对象,显式定义的对象是类属性,所有对象都共享
string name;
void show(){
cout << "this is test for " << this->name << endl;
}
};
Test::Test(string name){
this->name = name;
cout << "this is constructor for " << this->name << endl;
};
Test::~Test(){
cout << "this is destructor for " << this->name << endl;
};
int main(){
//malloc需要手动计算申请内存大小,返回内存需要强制转换
int *intarray = (int *) malloc(sizeof(int)*ARRAY_SIZE);
for(int i = 0; i<ARRAY_SIZE; i++){
*(intarray + i) = i ;
}
for(int i = 0; i<ARRAY_SIZE; i++){
cout << *(intarray + i) ;
}
cout << endl;
//malloc申请的内存需要free释放对应指针
free(intarray);
//注意释放后置NULL,以免后续访问野指针
intarray = NULL;
//注意new 分配数组内存的方式
int * intarray1 = new int[ARRAY_SIZE];
for(int i = 0; i<ARRAY_SIZE; i++){
*(intarray1 + i) = i ;
}
for(int i = 0; i<ARRAY_SIZE; i++){
cout << *(intarray1 + i) ;
}
cout << endl;
//Test test;
//虽然malloc也可申请对象内存,但不推荐
//new 直接返回类指针,无需像malloc一样需要强制类型转换,且new会调用构造函数
Test * testp = new Test("test1");
testp->show();
//使用new申请的内存需要delete释放,释放时隐式子调用析构函数
delete testp;
//直接通过类名在堆栈上创建对象,默认调用构造函数
Test test2("test2");
test2.show();
//test2并未显示释放对象内存,但程序结束会隐式调用析构函数
return 0;
}
以上代码输出结果如下:
0123456789
0123456789
this is constructor for test1
this is test for test1
this is destructor for test1
this is constructor for test2
this is test for test2
this is destructor for test2