C 11 再談new和delete 記憶體池

2021-10-09 03:01:18 字數 3194 閱讀 4628

再回顧一下new和malloc的區別

(重點!!!面試必問)new和malloc 的區別

1、malloc的返回值不安全需要進行型別轉換,而new不需要。

2、new是乙個關鍵字、malloc是乙個函式

3、malloc需要使用者輸入開闢記憶體的位元組大小,呢問,不需要計算開闢記憶體的大小。

4、new開闢記憶體失敗丟擲bad_alloc異常,malloc開闢記憶體失敗返回空指標

5、malloc在堆上開闢記憶體,new開闢的空間叫做自由儲存區。

6、malloc只能開闢空間不負責初始化,new不僅可以開闢空間還可以初始化

7、開闢動態陣列的時候new [i] 而malloc(總位元組數)

new1、開闢記憶體

operator new系統

2、呼叫建構函式

delete

1、呼叫析構函式

2、釋放物件的記憶體

new和delete混用:在沒有進行初始化的時候陣列和單個元素之間的new和delete可以混合使用

new test[5]實際上開闢的位元組還要加4個位元組,用來儲存對物件個數

自定義的類型別,有析構函式,為了呼叫正確的析構函式,那麼開闢物件陣列的時候,會多開闢四個位元組,記錄物件個數

**/*

靜態鍊錶要用指標而不用游標是因為游標可能無法唯一標識記憶體單元

*/const

int mem_size =3;

template

<

typename t>

class

mem_pool

return ppm;

}void

*alloc

(size_t size)

pcur-

>pnext =

null;}

void

* rt = pool;

pool = pool-

>pnext;

return rt;

}void

dealloc

(void

* ptr)

nptr-

>pnext = pool;

pool = nptr;

}private

:mem_pool()

mem_pool

(const mem_pool&)

;struct node//

public

: t val;

node* pnext;};

node* pool;

static mem_pool

* ppm;};

template

<

typename t>

mem_pool

* mem_pool

::ppm =

null

;#include

class

student

void

*operator

new(size_t size)

void

operator

delete

(void

* ptr)

private

: std::string mname;

std::string mid;

int mage;

static mem_pool

* pmm;};

mem_pool

* student::pmm = mem_pool

::getinstance()

;int

main()

**

用記憶體池實現乙個佇列:

template

<

typename t>

class

queue

~queue()

pfront = ptail =

null;}

void

push

(t val)

bool

empty()

void

pop(

) queueitem* pdelete = pfront-

>pnext;

pfront-

>pnext = pdelete-

>pnext;

delete pdelete;

} t front()

return pfront-

>pnext-

>mdata;

} t back()

return ptail-

>mdata;

}private

:class

queueitem

void

*operator

new(size_t size)

pcur-

>pnext =

null;}

void

* rt = pool;

pool = pool-

>pnext;

return rt;

}void

operator

delete

(void

* ptr)

queueitem* pptr =

(queueitem*

)ptr;

pptr-

>pnext = pool;

pool = pptr;

}public

: t mdata;

queueitem* pnext;};

queueitem* pfront;

queueitem* ptail;

static queueitem* pool;};

template

<

typename t>

typename queue

::queueitem* queue

::pool =

null

;int

main()

int rt = que.

front()

; que.

pop();

std::cout <<

"rt:"

<< rt << std::endl;

return0;

}

C 11的default和delete關鍵字

c11的新特性實在是太多了,這2個關鍵字關注的人倒是少了很多,其中有乙個原因便是編譯器支援得太慢了 vs到vs2013才支援上 不過這2個關鍵字那真是極為有用的,下面我們來看看。default關鍵字 首先我們有乙個字串類 class cstring 析構函式 cstring public void ...

C 11的default和delete的說明

在c 11標準中的描述是 default it means that you want to use the compiler generated version of that function,so you don t need to specify a body.delete it means...

new和delete解析 c 筆記

1.new delete 和operator new operator delete和malloc free的關係 new,delete運算子 當我們使用一條new表示式時,實際上執行了三步操作 第一步,new表示式呼叫乙個名為operator new 或者operator new 的標準庫函式,該...