#include <iostream>
#include <string>
#include <memory>
using namespace std;
int main() {
allocator<string> a; // define the allocator
size_t n;
cout << "Enter the size" << endl;
cin >> n;
string *p = a.allocate(n); // allocate a raw, unconstructed memory
auto q = p;
string tmp;
cout << "Enter the words" << endl;
while (cin >> tmp) {
a.construct(q++, tmp); // construct a object at q
}
cout << "Output the words" << endl;
auto z = p;
for (; z != q; ++z) {
cout << *z << " ";
}
cout << endl;
--q;
cout << "Destruct the memory" << endl;
while (q != p) {
a.destroy(q); // destruct the object at q
--q;
}
a.deallocate(p, 3); // deallocate the memory
return 0;
}
}
12.2 allocator类
最新推荐文章于 2025-07-28 16:21:04 发布
本文介绍了一个利用C++ STL中的allocator进行动态内存分配与管理的例子。通过用户输入来分配相应大小的字符串数组,并依次构造和析构这些字符串对象。此示例展示了如何在不使用new和delete的情况下管理内存。
3282

被折叠的 条评论
为什么被折叠?



