Jef*_*f M 10 c++ const reference
例如:
void f(const int&);
void g1() {
const int i = 42;
if (i == 42) f(i);
if (i == 42) f(i);
}
void g2() {
int i = 42;
if (i == 42) f(i);
if (i == 42) f(i);
}
Run Code Online (Sandbox Code Playgroud)
似乎"f"变异其参数应该是UB,因此应该允许编译器假设它不会发生并相应地进行优化.然而这两个功能将产生不同的组装.
我没有标准的副本.这不保证吗?
Kon*_*ski 13
根据标准,在C++中将指针指向const转换为指向非const的指针然后修改它(尽管它很混乱),只要指针指向的值未被声明为const.事实上,C++提供了一个关键字来做这样的演员表const_cast.
例如,这很好.
int a = 2;
const int* b = &a;
*const_cast<int*>(b) = 4;
Run Code Online (Sandbox Code Playgroud)
但这并不是指针指向的内存位置const.
const int a = 2;
const int* b = &a;
*const_cast<int*>(b) = 4;
Run Code Online (Sandbox Code Playgroud)
你的例子中的编译器必须假设一个被调用的函数可能会这样做,因为它对它一无所知,并为这种情况做好准备.