根据 C++11,下面的代码是否构成“未定义行为”(由于使用了 const_cast,请参见下面的引用)?
const void* p = operator new(123);
operator delete(const_cast<void*>(p));
来自 C++11 标准 (3.7.4.2.3) 的相关引述:
The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. Otherwise, the behavior is undefined if the value supplied to
operator delete(void*)
in the standard library is not one of the values returned by a previous invocation of eitheroperator new(std::size_t)
oroperator new(std::size_t, const std::nothrow_t&)
in the standard library
如果答案是否定的,请提供来自 C++11 标准的引述以证实这一点。
最佳答案
它不是未定义的。推理是这样的:
operator new
返回void*
,因此保证返回可修改(非常量)内存:[support.dynamic]void* operator new(std::size_t size);
const_cast
如果引用的对象不是 const,则丢弃常量是有效的:[expr.const.cast]§7,指的是 [dcl.type.cv],特别是§3+43 A pointer or reference to a cv-qualified type need not actually point or refer to a cv-qualified object, but it is treated as if it does; a const-qualified access path cannot be used to modify an object even if the object referenced is a non-const object and can be modified through some other access path.
4 Except that any class member declared
mutable
(7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.const_cast
不修改操作数的值:[expr.const.cast]§3:... The result of a pointer
const_cast
refers to the original object.
关于c++ - 全局分配函数和 const void*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24433250/