C++默认分配器 - 如果大小不等于传递给分配调用的大小,会发生什么?
20.6.9:
void deallocate(pointer p, size_type n);
- 要求:p 应是从 allocate() 获得的指针值。 n 应等于作为返回 p 的 allocate 调用的第一个参数传递的值。
- 作用: 释放 p 引用的存储空间。
- 备注: 使用::operator delete(void*) (18.6.1),但调用该函数时未指定。
如果n
不等于作为第一个参数传递给返回p
的allocate调用的值,会发生什么?不解除分配吗?抛出std::bad_alloc
? ...
编辑: 我对“应该发生什么”的实际意思是:在自定义实现中抛出或断言可以吗?
20.6.9:
void deallocate(pointer p, size_type n);
- Requires: p shall be a pointer value obtained from allocate(). n shall equal the value passed as the first argument to the invocation of allocate which returned p.
- Effects: Deallocates the storage referenced by p.
- Remarks: Uses ::operator delete(void*) (18.6.1), but it is unspecified when this function is called.
What should happen if n
doesn't equal the value passed as the first agrgument to the invocation of allocate which returned p
? Not deallocate? Throw std::bad_alloc
? ...
EDIT:
What I actually meant with "what should happen" was: Would it be okay to throw or assert in a custom implementation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与 C++ 标准中通常的情况一样,当没有明确说明任何内容时,违反要求会导致未定义的行为。 Shall 表示任何时候都必须,它是一个要求,而不是 C++ 标准中的一个选项。
例如,MSDN 是这么说的:
这意味着大小必须精确匹配,否则您会遇到未定义的行为。
As usual in C++ Standard, when nothing is stated explicitly, violating the requirements leads to undefined behavior. Shall means at all times must, it's a requirement, not an option in C++ Standard.
For example here's what MSDN says:
which means that the size must match precisely, otherwise you run into undefined behavior.
它没有说。这意味着这将是令人讨厌的“未定义行为”。
It doesn't say. Which means that it would be the nasty "undefined behviour".
标准中存在这一点,以允许底层分配器不知道其指针的分配大小。
例如,AmigaOS 分配器维护一个空闲内存块列表,甚至允许部分释放(即,如果我分配 1024 字节,然后在偏移量 256 处释放 512 字节,最终得到两个 256 字节分配),因此分配器希望我将此信息传递给释放器。
This is present in the standard to allow for underlying allocators that do not know the size of an allocation from its pointer.
For example, the AmigaOS allocator maintains a list of free memory blocks and even allows partial deallocation (i.e. if I allocate 1024 bytes, then free 512 bytes at offset 256, I end up with two 256 byte allocations), so the allocator expects me to pass this information to the deallocator.