考虑以下程序:
#include <iostream>
int main()
{
int x = 0;
const int* px = new (&x) const int(0);
x = 1;
std::cout << *px; // 1?
}
Run Code Online (Sandbox Code Playgroud)
它在GCC 4.8下编译(并产生"预期"输出),但我怀疑它完全是UB,因为动态对象具有类型const int(仍然是类型的一部分).但是,那么,如果是这样,为什么编译器不能阻止我违反const正确性呢?
例如:
const int* pc = new const int(3); // note the const
int* p = const_cast<int*>(pc);
*p = 4; // undefined behavior?
Run Code Online (Sandbox Code Playgroud)
特别是,编译器能否优化掉堆分配的堆*pc?
如果没有,修改,试图*pc通过p仍然构成未定义的行为-如果是这样,为什么呢?
c++ heap-memory const-cast compiler-optimization undefined-behavior