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

标签 c++ stl standards allocator

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

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): 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 ]

根据上面的表 27,p是“类型 XX::pointer 的值,通过调用 a1.allocate 获得,其中 a1 == a ”(其中 XX 是“类型 allocator_traits<X> ”,而 X 是“类型 T 的分配器类” ”)。此外,aa1是“类型 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/

相关文章:

c - "p = p + (*p)++ * 3 + c;"会导致未定义的行为吗?

standards - ISO 标准街道地址?

c++ - 如何确保函数在任何全局变量构造函数之前执行?

c++ - gcov 报告的析构函数中的分支是什么?

c++ - std::ostringstream 运算符重载搜索顺序?

c++ - 如何在 std::map 中使用表示不透明字节的类?

c++ - 为什么顺序容器同时具有 size_type 和 difference_type?

c++ - C++ 中的函数组合

c++ - MFC如何将两个对话框合并为一个对话框?

c++ - 初始化结构值