前言:
随笔,记录一下malloc 与 new 的区别。
一、在C++中malloc 是什么?
- C++ 中的 malloc free 的问题:
- (1) 程序员必须确定对象的长度
- (2) malloc 返回一个 void 指针, C++ 不允许将 void 赋值给其他任何指针,必须强制
- (3) malloc 可能申请内存失败,所以必须判断返回值来确保内存分配成功
- (4) 用户在使用对象之前必须记住对他初始化,构造函数不能显示调用初始化(构造函数是由编译器调用的),用户有可能忘记调用初始化函数
- 总结: C 的动态内存分配太复杂,容易令人混淆,是不可接受的
二、new
- C++ 中推荐使用 new,delete
- new 操作符能确定在调用构造函数初始化之前,所有不用显式确定调用是否成功
- delete 表达式先调用析构函数,然后释放内存
三、例子
代码如下(示例):
#include <iostream>
extern "C"
{
#include <stdio.h>
#include <malloc.h>
#include <string>
}
using namespace std;
class Student
{
public:
int id;
string name;
};
int main(int argc, char const* argv[])
{
int size = 10;
Student* st = (Student*)malloc(sizeof(Student) * size);
Student* st2=new Student[10];
for (Student* i = st; i < st + size; i++)
{
i->id = 123;
//i->name = "qiumc";
}
(st+1)->id=999;
st2->id=888;
st2[1].id=777;
cout << "st[0].id:" << st[0].id <<endl;
cout << "st[1].id:" << st[1].id <<endl;
cout << "st2.id:" << st2[0].id <<endl;
cout << "st2[1].id:" << st2[1].id <<endl;
free(st);
// 如果要释放st内存,仅仅需要free(st);既可以,不能把st当做一个数组,进行逐个释放。
delete []st2;
return 0;
}
总结
由以上代码可知,malloc与new都可以在c++中申请堆空间,不过要注意,malloc是函数,而new是一个操作符。
1万+

被折叠的 条评论
为什么被折叠?



