[問題] allocator

看板C_and_CPP (C/C++)作者 (這才是人生)時間13年前 (2012/11/22 20:42), 編輯推噓0(0010)
留言10則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) None 問題(Question): Allocator的作用是?? 程式碼(Code):(請善用置底文網頁, 記得排版) #include <list> #include <iostream> using namespace std; #if _MSC_VER > 1020 // if VC++ version is > 4.2 using namespace std; // std c++ libs implemented in std #endif typedef list<int, allocator<int> LISTINT; void main() { int rgTest1[] = {5,6,7}; int rgTest2[] = {10,11,12}; LISTINT listInt; LISTINT listAnother; LISTINT::iterator i; // Insert one at a time listInt.insert (listInt.begin(), 2); listInt.insert (listInt.begin(), 1); listInt.insert (listInt.end(), 3); // 1 2 3 for (i = listInt.begin(); i != listInt.end(); ++i) cout << *i << " "; cout << endl; // Insert 3 fours listInt.insert (listInt.end(), 3, 4); // 1 2 3 4 4 4 for (i = listInt.begin(); i != listInt.end(); ++i) cout << *i << " "; cout << endl; // Insert an array in there listInt.insert (listInt.end(), rgTest1, rgTest1 + 3); // 1 2 3 4 4 4 5 6 7 for (i = listInt.begin(); i != listInt.end(); ++i) cout << *i << " "; cout << endl; // Insert another LISTINT listAnother.insert (listAnother.begin(), rgTest2, rgTest2+3); listInt.insert (listInt.end(), listAnother.begin(), listAnother.end()); // 1 2 3 4 4 4 5 6 7 10 11 12 for (i = listInt.begin(); i != listInt.end(); ++i) cout << *i << " "; 補充說明(Supplement): 其實我只是想要問 typedef list<int, allocator<int> LISTINT; 這行中的allocator<int>這個的用意??? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 36.239.251.183

11/23 02:06, , 1F
我也想知道有沒有什麼實例...XD
11/23 02:06, 1F

11/23 02:51, , 2F
我沒記錯的話std::allocator有void的specialization 但
11/23 02:51, 2F

11/23 02:52, , 3F
我不記得why & how XD...問到實例 我在想如果需要debug
11/23 02:52, 3F

11/23 02:52, , 4F
memory allocation的時候可能會想自己寫個allocator
11/23 02:52, 4F

11/23 02:53, , 5F
然後搭配placement new 吧...吧 我只是在想而已 從來沒
11/23 02:53, 5F

11/23 02:53, , 6F
注意到有人這樣做 我自己也沒這樣做過
11/23 02:53, 6F

11/23 10:11, , 7F
有時候考量到效率或是為了要避免 fragmentation
11/23 10:11, 7F

11/23 10:13, , 8F
會先配置一大塊空間,自己做記憶體管理。
11/23 10:13, 8F

11/23 10:13, , 9F
這時候就不能用預設的 allocator,而必須自己寫一個。
11/23 10:13, 9F

11/24 01:47, , 10F
所以說 應該是為了考量記憶體配置才需要用的指令囉
11/24 01:47, 10F
文章代碼(AID): #1GhXt9gw (C_and_CPP)
文章代碼(AID): #1GhXt9gw (C_and_CPP)