STL原始碼第二章 allocator

2021-10-03 09:48:57 字數 2345 閱讀 1629

#ifndef pch_h

#define pch_h

#include

#include

#include

//for ptrdiff_t,size_t

#include

//for exit()

#include

//for uint_max

#include

namespace jj

return tmp;

}template

<

typename t>

inline

void

_deallocator

(t* buffer)

//刪除記憶體塊

template

<

typename t1,

typename t2>

inline

void

_construct

(t1* p,

const t2&value)

template

<

typename t>

inline

void

_destroy

(t* ptr)

template

<

typename t>

class

allocator

; pointer allocate

(size_type n,

const

void

* hint =0)

//任何型別指標

void

deallocate

(pointer p, size_type n)

void

construct

(pointer p,

const t& value)

void

destroy

(pointer p)

pointer address

(reference x)

const_pointer const_address

(const_referenc x)

size_type max_size()

const

return

size_type

(uint_max /

sizeof

(t));}

;}#endif

第一種 預設初始化

class

test};

intmain()

輸出為1

第二種 直接初始化

class

test

test

(std::string s)};

intmain()

輸出為

空test

第三種 花括號列表初始化

```cpp

class test

test(std::string s) };

int main()

; /*or 顯式*/

test t = test{};

std::cout << std::endl;

}

輸出為1

test t和test t()它們應該都是呼叫的無參建構函式,為什麼產生的結果不一樣呢?

我們知道test t會呼叫預設建構函式,如果沒有定義預設建構函式,且類中有其他建構函式(不會自動生成合成建構函式)那麼編譯器會報錯:沒有合適的預設建構函式可用

所以此時我們程式會輸出1

那麼test()呢?我們知道test()會生成乙個沒有物件名稱的臨時物件,這個物件直接初始化,使用圓括號提供初值是用來構造(construct)物件,因此可以知道,所謂的直接初始化就是顯式的呼叫相應的建構函式,所以test()也會呼叫預設建構函式。

此時程式也會輸出1

但是為什麼test t()的結果就是空呢?

這裡是因為vs編譯器會認為我們忘記了新增實參,所以會報乙個警告c4930::未呼叫原型函式(是否是有意用變數定義的?),其實在這裡編譯器會將test t()看做了乙個函式宣告,宣告為乙個不接受引數返回test類物件的函式。所以編譯器就糊塗了,你這到底是函式宣告還是類物件初始化,老子不幹了,所以直接會輸出乙個空,如果想要初始化這個t,可以將括號改為花括號或者用等號顯式初始化。

test t

;test t =

test()

;

STL原始碼剖析 第二章 空間配置器

c 記憶體配置操作和釋放操作如下 1 class foo 2 foo pf new foo 配置記憶體,然後構造物件 3delete pf 將物件析構,然後釋放記憶體 記憶體配置操作由 alloc allocate 負責,記憶體釋放操作由 alloc deallocate 負責 物件構造操作由 co...

第二章 STL簡介

容器共同操作操作 insert pos,e 將元素e的拷貝安插於迭代器pos所指的位置 erase beg,end 移除 beg,end 區間內的所有元素 clear 移除所有元素 c.size 返回元素個數 c.empty 判斷容器是否為空 c.max size 返回元素最大可能數量 固定值 c....

第二章 STL簡介

1 容器 container 2 迭代器 iterator 3 演算法 algorithm 4 函式物件 function object 5 介面卡 adaptor 6 空間配製器 allocator 構造 拷貝和析構 非變動操作 基本原理 將插入的值 第乙個運算元 與樹根 第二個運算元 紅黑樹,二...