尽量以new和delete取代malloc和free
来源:互联网 发布:中国移动网络电视盒子 编辑:程序博客网 时间:2024/05/16 23:40
记得一次面试被问到new和malloc的区别,答曰:new是一个操作符,malloc是一个函数。面试官曰:也就是没有区别是吧!晕,难道我说的不是区别吗?看来我没有说到他想听到的东西。也罢,平常书读的少了,思考的也不多,对这些问题总是说不到本质上去。所以励志读遍IT界的大牛神书,多多的思考,多多的实践!
malloc和free是C语言中提供我们用于堆内存分配的库函数,那时还没有C++的构造函数,析构函数的概念,也就对它们一无所知。
欲取得10个string对象所形成的数组空间,有两种方法
string *stringArray1 = static_cast<string*>(malloc(10*sizeof(string)));
string *stringArray2 = new string[10];
两者的区别是stringArray1将指向能够放置10个string对象的内存空间,但其中没有任何对象被初始化。
stringArray2指向由10个构造妥当的string对象所构成的数组,每一个元素都可以被安全的运用于任何需要string的行动上。
在释放到内存时我们会这样做:
free(stringArray1);
delete [] stringArray2;
free会释放掉stringArray1所指的内存,但不会调用其中的string对象的destructors。要命的地方在于如果string对象本身亦配置有内存,那么那些内存就全部遗失了。但如果以delete施加于stringArray2身上,在内存被释放之前,数组中的每一个对象的destructor都会被调用一遍。
最后需要注意的是new/deelte,malloc/free要配对,切忌混用。混用时会有“未定义”的错误。
所谓“未定义”的意思是:它在开发阶段没有问题,它在测试阶段没有问题,但是它会在你最重要的客户面前突然爆发。
- 尽量以new和delete取代malloc和free
- 尽量用new和delete而不用malloc和free
- 尽量用new和delete而不用malloc和free
- 尽量用new和delete而不用malloc和free malloc和free
- malloc/free和new/delete
- new/delete 和 malloc/free
- malloc free 和new delete
- malloc/free和new/delete
- malloc/free 和 new/delete
- malloc/free和new/delete
- new/delete和malloc/free
- malloc/free和new/delete
- new、delete和malloc、free
- malloc-free和new-delete
- new/delete和malloc/free
- malloc/free和new/delete
- malloc()、free()和new、delete
- new,delete和malloc,free
- 简单直接Linux下开启Core功能
- sqlserver表删除比较
- fzu——Problem 2088 最长队名
- 我在登录界面的输入错误值,为什么不会显示出错误提示呢?(这是代码简略)
- Android源码分析:RIL代码分析
- 尽量以new和delete取代malloc和free
- Latent Semantic Analysis (LSA) Tutorial - Advantages, Disadvantages, and Applications of LSA
- Linux防火墙设置
- ITU-T E.800 有关服务质量(QoS)的术语定义
- 关于Calendar的一些方法
- 谁才是真正的资深开发者?
- Hbase源码分析 RowCounter
- 深入理解Java内存模型
- saving-the-android-webview-cache-on-the-sd-card