const在这里允许(理论上)优化吗? [英] Does const allow for (theoretical) optimization here?
问题描述
请考虑以下代码段:
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
?