您的位置:首页 > 其它

STL源码解析-02配置器-01使用

2011-12-02 14:55 507 查看
#include <iostream>

using namespace std;

class test{
public:
int value;
test() {cout << "construct value: none\n";}
test(const test& mt) {value = mt.value;cout << "copy constructor value:" << value << endl;}
~test() {cout << "~test" << endl;}
};

int main()
{
allocator<int> iall;//可以用已有allocator进行构造

int temp1;
cout << "the address of variable temp1: " << iall.address(temp1) << endl; //传入变量的引用,返回变量的地址
cout << "after the first value, the max_size of the allocator: " << iall.max_size() << endl; //返回allocator最大能分配的空间,不变
int temp2;
cout << "the address of variable temp2: " << iall.address(temp2) << endl;
cout << "after the second value, the max_size of the allocator: " << iall.max_size() << endl;

int *p = iall.allocate(3); //在堆中分配大小,不做其他初始化事情,大小为4的倍数。
*(p+1) = 34;
*(p+200) = 77;
cout << "allocate 10, the second value is :" <<*(p+200)<< endl;
cout << "the address of variable p: " << iall.address(*p) << endl;
cout << "the address of variable p+9: " << iall.address(*(p+9)) << endl;
cout << "after the third value, the max_size of the allocator: " << iall.max_size() << endl;
iall.deallocate(p,1); //收回指定的大小,并没有释放空间,只是将大小放到相应的lsit下,指定的大小没啥用啊,按照申请时的大小回收。
*(p+7) = 78;
cout << "deallocate 5, the seven value is :" <<*(p+7)<< endl;

int *q = iall.allocate(7);//如果p与q申请的地址相同,且p已经deallocate掉,此时q的地址是p的地址。
cout << "the address of variable p: " << iall.address(*q) << endl;

test *pt;
test t;
cout << "construct test object over.\n";
t.value = 54;
allocator<test> tall;
pt = tall.allocate(1);//先给指针分配好空间,再调用construct函数,此时不对对象实例化。
cout << "the address of variable pt: " << tall.address(*pt) << endl;
tall.construct(pt,t);//给传入的指针,调用拷贝构造函数
tall.destroy(pt);//调用指针的析构函数
cout << "the second value is :" <<*(p)<< endl;

cout << "~over\n";
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: