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 标准 ( 的相关引述:

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++ - btCompoundShape 添加了额外的形状

c++ - boost::is_member_function_pointer_of?

c++ - 关联容器所需的比较器

c++ - 如何正确地将 C 字符串传递给可变参数模板函数内的 lambda

c++ - 合法使用 initializer_list 来初始化具有派生类型的对象吗?


c++ - 如何实现一个支持模板协变的泛型工厂?

c++ - C++ 中的货币格式

c++ - std::basic_filebuf::seekpos 的文档

c - scanf(),字段宽度,inf 和 nan