条款三:尽量用new和delete而不用malloc和free
2014-08-04 14:24
239 查看
malloc和free(及其变体)会产生问题的原因在于它们太简单:他们不知道构造函数和析构函数。假设用两种方法给一个包含10个string对象的数组分配空间,一个用malloc,另一个用new:
string *stringarray1 = static_cast<string*>(malloc(10 * sizeof(string))); string *stringarray2 = new string[10];其结果是,stringarray1确实指向的是可以容纳10个string对象的足够空间,但内存里并没有创建这些对象。换句话说,stringarray1其实一点用也没有。相反,stringarray2指向的是一个包含10个完全构造好的string对象的数组,每个对象可以在任何读取string的操作里安全使用。假设你想了个怪招对stringarray1数组里的对象进行了初始化,那么在你后面的程序里你一定会这么做:
free(stringarray1); delete [] stringarray2;// 参见条款5:这里为什么要加上个"[]"调用free将会释放stringarray1指向的内存,但内存里的string对象不会调用析构函数。如果string对象象一般情况那样,自己已经分配了内存,那这些内存将会全部丢失。相反,当对stringarray2调用delete时,数组里的每个对象都会在内存释放前调用析构函数。
相关文章推荐
- Effective C++学习笔记:条款3:尽量用new和delete而不用malloc和free
- Effective C++:条款3:尽量用new和delete而不用malloc和free
- 条款3:尽量用new和delete而不用malloc和free
- Effective C++条款3:尽量用new和delete而不用malloc和free
- 条款3:尽量用new和delete而不用malloc和free
- 条款3,4:尽量用new和delete而不用malloc和free 尽量使用c++风格的注释
- 条款3:尽量用new和delete而不用malloc和free
- 尽量用new和delete而不用malloc和free
- 尽量用new和delete而不用malloc和free
- 【让你的C++程序更加高效】条款03:尽量使用new/delete而不是malloc/free
- Effective c++ 条款3、6:new、delete和malloc、free
- 尽量以new和delete取代malloc和free
- 动态分配的标准写法(new, delete; malloc, free)
- New delete 与malloc free 的联系与区别
- malloc/free与new/delete的区别与联系
- malloc/free vs new/delete
- malloc/free new/delete
- new/delete与malloc/free的区别是什么
- 内存管理——关于malloc/free与new/delete
- The differences between new(delete) and malloc(free) in c/c++