【翁恺】09-new and delete

dynamic memory allocation   在堆里面申请空间

  • new
    • new int;  // 分配一块 int 空间
    • new Stash; // 分配Stash对象的空间   然后调用构造函数初始化
    • new int[10] // 分配10个int 空间
  • delete  // 给它一个地址
    • delete p;  // 
    • delete[] p;

相当于c中mallocefree

任何运算都有结果,new操作返回的是地址

动态制造对象。 new 带着[ ], delete 也要带着[]。

delete p所指的对象时候,析构函数先被调用,然后空间被回收。

new and delete

  • new is the way to allocate memory as a program runs. Pointers become the only access to that memory

  • delete enables you to return memory to the memory pool when you are finished with it

dynamic arrays

int * psome = new int [10];  // 动态申请数组

  • the new operator returns the address of the first element of the block

delete [] psome;  // []释放,10个析构都会被调用, 不带[]只有一个被析构

  • the presence of the brackets tells the program that it should free the whole array,not just the element

 

tips for new an delete

  • don't use delete to free memory that new didn't allocate

  • don't use delete to free the same block of memory twice in succession(连续)

  • use delete[] if you used new [] to allocate an array

  • use delete (no brackets) if you used new to allocate an array

  • it's safe to apply delete to the null pointer (noting happens)

new了对象但是不delete,因为我们现在的程序都是跑一下,我们的操作系统都是多进程,程序每次运行都是一个进程,操作系统给分配了虚拟空间,当程序结束后,空间会被回收,即使申请了内存没有释放,打开文件没有关闭,但是程序结束后都结束了。

但是如果程序要一直运行,那么会存在内存泄漏问题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

理心炼丹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值