问题描述
请考虑以下代码段:
void foo(const int&);
int bar();
int test1()
{
int x = bar();
int y = x;
foo(x);
return x - y;
}
int test2()
{
const int x = bar();
const int y = x;
foo(x);
return x - y;
}
在我对标准的理解中,test2
中的foo
不允许x
和y
进行更改,而在test1
中的foo
不能对其进行更改(例如,const_cast
从const int&
中删除const
,因为所引用的对象实际上不是test1
中的const).
In my understanding of the standard, neither x
nor y
are allowed to be changed by foo
in test2
, whereas they could be changed by foo
in test1
(with e.g. a const_cast
to remove const
from the const int&
because the referenced objects aren't actually const in test1
).
现在,无论gcc,clang还是MSVC都似乎都没有将test2
优化为foo(bar()); return 0;
,而且我可以理解,他们不想浪费优化,而将这种优化传递给实践的人很少.
Now, neither gcc nor clang nor MSVC seem to optimize test2
to foo(bar()); return 0;
, and I can understand that they do not want to waste optimization passes on an optimization that only rarely applies in practice.
但是我至少对我对这种情况的理解是正确的,还是我缺少在test2
中修改x
的某种合法方法?
But am I at least correct in my understanding of this situation, or am I missing some legal way for x
to be modified in test2
?
推荐答案
该标准在 [dcl.type.cv] :
根据 [basic.life] :
这意味着将x - y
优化为零是有效的,因为任何在foo
中修改x
的尝试都会导致不确定的行为.
This means that the optimization of x - y
to zero is valid because any attempt to modify x
in foo
would result in undefined behavior.
一个有趣的问题是,是否有理由在现有编译器中不执行此优化.考虑到const对象定义对于test2
是局部的,并且事实是在同一函数中使用的,因此此处不适用诸如支持符号插入之类的常见异常.
The interesting question is if there is a reason for not performing this optimization in existing compilers. Considering that the const object definition is local to test2
and the fact is used within the same function, usual exceptions such as support for symbol interposition do not apply here.
这篇关于const在这里允许(理论上)优化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!