new/delete和malloc/free
来源:互联网 发布:mysql type ref 编辑:程序博客网 时间:2024/04/29 23:56
假如通过malloc和new的方法给包含10个string对象的数组分配空间
string* strary_one = static_cast<string*>(malloc(10*sizeof(string)));string* strary_two = new string[10];
其结果是strary_one确实指向能够容纳10个string对象的内存空间,但并没有创建这些对象,而strary_two指向的是包含10个已经完全构建好的string对象数组.
在程序结束时需要释放这些内存
free(strary_one);//This is notcorrect, only delete one elementdelete strary_two;delete[] strary_two;
调用free会释放其指向的内存,但数组中的string对象并不会调用析构函数,若string对象像普通对象,自身已分配内存,那么这些内存将会丢失;而delete在释放每个对象时都会先调用其析构函数.
所以建议尽量使用new/delete
int* p_scalar = new int(5);//Does not create 5 elements, but initializes to 5int* p_array = new int[5];//Creates 5 elements
0 0
- 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
- malloc/free和new/delete
- malloc/free和new/delete
- malloc/free和new/delete
- new/delete 和 malloc/free
- Windows环境下MySQL5.5的安装与配置
- Android学习总结(一)
- 使用matlab进行非线性方程组求解
- GoogleTest的使用01
- CSS3 遮罩蒙版效果 分栏效果
- new/delete和malloc/free
- POJ 1860 Currency Exchange(SPFA 判断有无“正”环)
- Java的final关键字
- https介绍
- Struts1.x框架基本原理
- 关于synchronized关键字的一点补充
- C++11在时空性能方面的改进
- 使用HTML制作网页
- NSURLSessionConfiguration