内存分配器是否应该与多态类型一起使用? 例如,下面的代码正确吗?
class A { ... };
class B { ... };
class C : public A, public B { ... };
std::allocator<C> alloc_c;
auto p_c = alloc_c.allocate(1);
// CASE A: pointer to A and to C point to the same memory address
std::allocator<A> alloc_a(alloc_c);
alloc_a.deallocate((A*)p_c, 1);
// CASE B: pointer to B and to C point to the different memory addresses
std::allocator<B> alloc_b(alloc_c);
alloc_b.deallocate((B*)p_c, 1);
当然,要么是情况 A,要么是情况 B,而不是两者兼而有之。
最佳答案
17.6.3.5 中的表 28 定义 deallocate
这样:
a.deallocate(p,n)
: Alln
T
objects in the area pointed to byp
shall be destroyed prior to this call.n
shall match the value passed toallocate
to obtain this memory. Does not throw exceptions. [ Note:p
shall not be singular.—end note ]
根据上面的表 27,p
是“类型 XX::pointer
的值,通过调用 a1.allocate
获得,其中 a1 == a
”(其中 XX
是“类型 allocator_traits<X>
”,而 X
是“类型 T
的分配器类” ”)。此外,a
和a1
是“类型 X&
的值”。
换句话说,该标准并没有设想传递到 deallocate
由不同类型的分配器分配的指针。它仅指定 deallocate
时发生的情况给定一个由同一分配器对象分配的指针,或者与此分配器比较的相同类型的另一个分配器。
此时,我们已经
1.3.24 undefined behavior
behavior for which this International Standard imposes no requirements [ Note: Undefined behavior may be expected when this International Standard omits any explicit definition of behavior...]
关于C++ 内存分配器和多态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27878843/