AFAIK std :: allocator由库引入,以分配未初始化的未构造内存块。因此:
std::allocator<int> a;
auto ptr = a.allocate(100);
auto e = ptr;
while (e != ptr + 5)
a.construct(e++, 0);
for (auto tmp = ptr; tmp != e; )
std::cout << *tmp++ << ", ";
std::cout << std::endl;
std::allocator<int> a2;
std::allocator<int> a3 = a;
for (auto tmp = ptr; tmp != e; )
a.destroy(tmp++);
//for (auto tmp = ptr; tmp != e; )
// a2.destroy(tmp++); // is it UB using a2 here to destroy elements?
//for (auto tmp = ptr; tmp != e; )
// a3.destroy(tmp++); // is it UB also?
a.deallocate(ptr, 100); // ok
//a2.deallocate(ptr, 100); // UB or OK?
//a3.deallocate(ptr, 100); // UB or ok?
我不确定的是是否使用另一个分配器a2
,a3
对象(其中一个)释放由a
分配的内存是否是未定义的行为?
如果可以,为什么像std::vector
这样的类具有分配器对象,而不仅创建一个临时对象来分配/取消分配内存?
请澄清以上问题。谢谢。
我对标准的阅读说这是未定义的行为。 Table 34: Cpp17Allocator requirements [tab:cpp17.allocator]个状态,用于