网站首页 > 文章精选 正文
一、new是操作符,而malloc是函数
void* malloc(size_t);
void free(void*);
void *operator new (size_t);
void operator delete (void *);
void *operator new[] (size_t);
void operator delete[] (void *);
二、new在调用的时候先分配内存,在调用构造函数,释放的时候调用析构函数。
#include <iostream>
using namespace std;
class Player{
public:
Player(){
cout << "call Player::ctor\n";
}
~Player(){
cout << "call Player::dtor\n";
}
void Log(){
cout << "i am player\n";
}
};
int main(){
cout << "Initiate by new\n";
Player* p1 = new Player();
p1->Log();
delete p1;
cout << "Initiate by malloc\n";
Player* p2 = (Player*)malloc(sizeof(Player));
p2->Log();
free(p2);
}
输出结果为:
Initiate by new
call Player::ctor
i am player
call Player::dtor
Initiate by malloc
i am player
三、new是类型安全的,malloc返回void*
四、new可以被重载
五、new分配内存更直接和安全
六、malloc 可以被realloc
#include <iostream>
using namespace std;
int main(){
char* str = (char*)malloc(sizeof(char*) * 6);
strcpy(str, "hello");
cout << str << endl;
str = (char*)realloc(str, sizeof(char*) * 12);
strcat(str, ",world");
cout << str << endl;
free(str);
}
输出结果为:
hello
hello,world
七、new发生错误抛出异常,malloc返回null
八、malloc可以分配任意字节,new 只能分配实例所占内存的整数倍数大小
猜你喜欢
- 2024-12-30 简单的使用SpringBoot整合SpringSecurity
- 2024-12-30 Spring Security 整合OAuth2 springsecurity整合oauth2+jwt+vue
- 2024-12-30 DeepSeek-Coder-V2震撼发布,尝鲜体验
- 2024-12-30 一个数组一行代码,Spring Security就接管了Swagger认证授权
- 2024-12-30 简单漂亮的(图床工具)开源图片上传工具——PicGo
- 2024-12-30 Spring Boot(十一):Spring Security 实现权限控制
- 2024-12-30 绝了!万字搞定 Spring Security,写得太好了
- 2024-12-30 SpringBoot集成Spring Security springboot集成springsecurity
- 2024-12-30 SpringSecurity密码加密方式简介 spring 密码加密
- 2024-12-30 Spring cloud Alibaba 从入门到放弃
- 07-01IT之家学院:升级Win10遭遇0xc0000017错误的解决办法
- 07-01网购笔记本电脑重装系统一直蓝屏,蓝屏代码0xc0000428
- 07-01Win7出现应用程序无法正常启动提示0xc0000142,解决方法方法来了
- 07-01win10蓝屏错误代码0xc0000428三种方法解决开机进不去系统
- 07-01【家里电脑蓝屏,拯救电脑的过程,给不懂电脑的人参考】
- 07-01更新Windows 10/11后 Chrome、Edge浏览器发生0xc0000022报错与崩溃
- 07-01win11错误代码0xC004F074无法激活修复的解决办法
- 07-01电脑开机黑屏,无法进系统,提示0xc000014c怎么办?
- 最近发表
-
- IT之家学院:升级Win10遭遇0xc0000017错误的解决办法
- 网购笔记本电脑重装系统一直蓝屏,蓝屏代码0xc0000428
- Win7出现应用程序无法正常启动提示0xc0000142,解决方法方法来了
- win10蓝屏错误代码0xc0000428三种方法解决开机进不去系统
- 【家里电脑蓝屏,拯救电脑的过程,给不懂电脑的人参考】
- 更新Windows 10/11后 Chrome、Edge浏览器发生0xc0000022报错与崩溃
- win11错误代码0xC004F074无法激活修复的解决办法
- 电脑开机黑屏,无法进系统,提示0xc000014c怎么办?
- 电脑错误代码0xc0000001怎么办,三种解决方法介绍
- Windows错误代码0xc0000001?多种修复方法完美解决win10蓝屏代码
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)
- mysql数据库面试题 (57)