c++ - 全局分配函数和 const void*

标签 c++ c++11 language-lawyer

根据 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 either operator new(std::size_t) or operator new(std::size_t, const std::nothrow_t&) in the standard library

如果答案是否定的,请提供来自 C++11 标准的引述以证实这一点。

最佳答案

它不是未定义的。推理是这样的:

  1. operator new 返回 void*,因此保证返回可修改(非常量)内存:[support.dynamic]

    void* operator new(std::size_t size);
    
  2. const_cast 如果引用的对象不是 const,则丢弃常量是有效的:[expr.const.cast]§7,指的是 [dcl.type.cv],特别是§3+4

    3 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.

  3. 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/

相关文章:

c++ - 什么是执行宽字符集及其编码?

c++ - 如何用其他值对空格进行冒泡排序?

c++ - 将对象添加到 vector 时出现编译器错误

c++ - 格式化 IO 函数 (*printf/*scanf) 中的转换说明符 %i 和 %d 有什么区别

c++ - 向 vector 的所有元素添加一个 int

c++ - 具有类作为键的映射,允许重复键

c# - 消除 visual studio 解决方案文件夹中的临时文件

c++ - 使用智能指针设计两个相互引用的类

c++ - C++11 标准中的核心常量表达式是什么?

一个对象可以有多个有效类型吗?