C++ 内存分配器和多态类型

C++ memory allocators and polymorphic types

内存分配器应该与多态类型一起使用吗? 例如,下面的代码是否正确?

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,不能两者兼而有之。

Table 17.6.3.5 中的 28 这样定义 deallocate

a.deallocate(p,n): All n T objects in the area pointed to by p shall be destroyed prior to this call. n shall match the value passed to allocate to obtain this memory. Does not throw exceptions. [ Note:p shall not be singular.—end note ]

根据上面的 Table 27,p 是 "a value of type XX::pointer, obtained by calling a1.allocate, where a1 == a"(其中 XX 是 "the type allocator_traits<X>",X 是 "an Allocator class for type T").此外,aa1 是 "values of type 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...]