new,delete和malloc,free以及allocatorT
一)new和delete,自己覺得一句話就是:最好同一作用域內,必須成對使用
先給出自己的認識:
malloc,free,申請和釋放一段heap堆中的內存。
new:申請heap內存并在申請的內存中放置用默認構造函數構造好的對象。(注意:對象內可能也有申請堆內存,new)
delete:完成了兩個工作,
1. 釋放對象內申請的堆內存。 所以會去調用析構函數。
2.?釋放對象本身占用的堆內存。類似free 對象指針。
如下例子,明白了,就應該基本初步認識了new和delete。
#include <stdio.h> #include <iostream> using namespace std;class myclass { public:myclass(const string& _name,const string& _des):name(_name),heaporstack(_des){pint=new int[10]{1,2,3,4,5,6,7,8,9,0};printf("%s Construt by %s. add of class:%0x\. add of int[] in class:%0x0 \n",name.c_str(),heaporstack.c_str(), this,pint);};~myclass(){delete[] pint;printf("%s Destory by %s. add of class:%0x\. add of int[] in class:%0x0 \n",name.c_str(),heaporstack.c_str(), this,pint);}string name;string heaporstack;int * pint;private:myclass(){} };int main() {myclass Mclass_local("Mclass_local","stack");myclass* Mclass_heap=new myclass("Mclass_heap","heap");delete Mclass_heap;Mclass_heap=0x0;return 0; }?
所以,使用基本原則:
1)成對使用。new 對 delete . new a[] ?對 delete [] a;
2)誰new誰delete。 mian方法中,new,那么main必須delete。 class 中new。那么class的析構函數~class{delete} 最好有delete。也就是最好同一作用域內。
3)delete后,必須把指針設置為空指針。當然在析構函數內其實不用寫。因為析構是最后執行的,類里面不太會有語句在析構之后執行。
?
二)C++還有一個std::allocator<T>
?
作用:某些類,需要預先分配用于創建新對象的內存,需要時再在預先分配的內存中構造新對象。也就是以空間換時間的策略。
比如vector。就是典型的這種類,先分配一定大小,加入數據時,如空間夠,不必要每次插入數據就申請一次空間,只有空間不夠才再次申請原空間的2倍內存。典型的預支內存空間換申請內存時間的策略。
常用的操作:
allocator<T> a; ? ?定義一個T類型的allocator對象。
a.allocate(n); ? ? ? 申請n個T大小的,未分配的空間。類似(T*) malloc(sizeof(T)*n)
a.deallocate(p,n) ?釋放內存,p為T*,n為釋放的T類型對象的數量。注意:T類型對象本身,如有需要釋放的資源,必須先釋放,a.deallocate(p,n)只是釋放對象本身的內存,而對象的建立又額外申請的資源,需要另外處理。
a.construct(p,t) ? 復制構造,用t來復制構造。相當于 new (p) T(t),這個是placement new的用法 ?new(place_address) type(initializer-list)
?
uninitialized_copy(startit,endit,it) ? startit,endit :要復制的開始迭代器地址和結束地址。it:要復制的迭代器地址。
(迭代器指向的類型是POD型別,不用構造,可以直接拷貝,不清楚具體處理,見鏈接,備了解。)
uninitialized_fill(startit,endit,obj) ??? startit,endit :要復制的開始迭代器地址和結束地址。it:要復制的對象。 使用復制構造函數填充內存
uninitialized_fill_n(startit,endit,obj,n) ??? startit,endit :要復制的開始迭代器地址和結束地址。it:要復制的對象。 n,要復制的數量。?使用復制構造函數填充內存
?
轉載于:https://www.cnblogs.com/lsfv/p/6006860.html
總結
以上是生活随笔為你收集整理的new,delete和malloc,free以及allocatorT的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DataTable添加列和行的三种方法
- 下一篇: FIFO跨时钟域读写