C++之new和delete

new 是一种运算符 会自己计算类型大小 申请空间 malloc对申请的空间不会初始化 new会按括号里的值进行初始化 delete 归还空间

new使用方式:1.运算符 2.函数 3.定位符

new运算符使用

1.计算使用空间的大小 2.通过malloc申请空间 3.用括号里的内容初始化该空间(调用构造函数) 4.返回地址给指针

 int main() {
     int* p = new int(10);
     cout << *p << endl;
     delete p;//p此时成为了空悬指针
     p = nullptr;
 }
 ​
 int main() {
     int n = 0;
     int* ip = nullptr;
     ip = new int[n];
     for (int i = 0; i < n; ++i) {
         *ip[i] = i;
     }
     for (int i = 0; i < n; ++i) {
         cout << ip[i] << endl;
     }
     delete[]ip;
     return 0;
 }

内存泄漏:地址丢失 堆空间耗损完全

 
int main(){
     int* ip = new(std::nothrow) int(10); // 1 2 3  4    throw std::bad_alloc
     delete ip;
     int* s = (int*)::operator new(sizeof(int), std::nothrow);
     //           (int*) malloc(sizeof(int));
     if (nullptr == s){}
 }
 ​
 int main() {
     int* ip = (int*)malloc(sizeof(int));
     new(ip) int(100);
     cout << *ip << endl;
     free(ip);
     return 0;
 }

定位new

 int main() {
     char buff[128];
     new(buff)int(0x12345678);
     new(buff + 4)int(10);
     return 0;
 }

对于内置类型new/delete/malloc/free可以混用

区别:

1.new/delete是c++中的运算符 malloc/free是函数 2.malloc申请内存空间时,手动计算大小,new只需要类型名,自动计算大小 3.malloc申请的内存空间不会初始化,new可以初始化 4.malloc返回值为void*,接收时必须强转,new不需要 5.malloc申请内存空间失败时,返回的值是NULL,使用时必须判空 new申请内存空间失败时抛出异常,所以要有捕获异常处理的程序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值