我的理解是,如果所讨论的对象基本上是 const 对象而不是 const 指针或对最初不是 const 的对象的引用,它只会是 UB。
这个想法是,本质上是 const 的数据可以加载到内存的只读部分中,而写入该部分是行不通的。但是,如果所讨论的对象基本上是可变的,则可以保证正常工作。
前任:
const int x = 4;
const int *y = x;
*const_cast<int*>(x) = 3; // UB - the pointed-to object may
// be in read-only memory or whatever.
int a = 7;
const int *b = a;
*const_cast<int*>(b) = 6; // Not UB - the pointed-to object is
// fundamentally mutable.
对于下面的评论,因为代码在评论中看起来很糟糕:
在标准的 §7.1.5.1/4 中,给出的示例是:
int i = 2;
const int * cip; // pointer to const int
cip = &i; // OK: cv-qualified access path to unqualified
...
int* ip;
ip = const_cast <int *>( cip ); // cast needed to convert const int* to int*
*ip = 4; // defined: *ip points to i, a non-const object
所以这是特别允许的。