网站首页 > 文章精选 正文
一、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 从入门到放弃
- 最近发表
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 稳压管的稳压区是工作在什么区 (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)