allocator類將分配內存空間、調用構造函數、調用析構函數、釋放內存空間這4部分操作分開,全部交給程序員來執行,不像new和delete
#include <iostream>
#include <string>int main()
{const int n = 10;std::allocator<std::string> alloc; // 定義一個用于分配string的allocator的對象std::string* const p = alloc.allocate(n); // 分配n個未初始化的string的內存,沒有調用string的構造函數std::string* q = p;while (q != p + n) { // p + n相當于p[n],即數組最后一個元素的下一個位置alloc.construct(q, 10, 'a'); // 通過q為每個string調用構造函數,構造函數參數由alloc.construct傳遞std::cout << "construct: " << * q << std::endl;q++; // q最終會指向最后一個string的下一個位置}while (q != p) {q--;std::cout << "destory: " << *q << std::endl;alloc.destroy(q); // 對q指向的string進行析構}alloc.deallocate(p, n); // 釋放內存空間,p必須是先前調用allocate時返回的指針,n必須是創建時allocate填入的數量
}