gpt4 book ai didi

c++ - const 是否允许在此处进行(理论上的)优化?

转载 作者:可可西里 更新时间:2023-11-01 16:18:34 25 4
gpt4 key购买 nike

考虑这个片段:

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;
}

在我对标准的理解中,xy 都不允许被 test2 中的 foo 改变>,而它们可以通过 test1 中的 foo 进行更改(例如使用 const_castconst int& 因为引用的对象在 test1 中实际上不是 const。

现在,neither gcc nor clang nor MSVC似乎将 test2 优化为 foo(bar()); return 0;,我可以理解他们不想将优化传递浪费在实践中很少应用的优化上。

但是我对这种情况的理解至少是正确的,还是我错过了一些在 test2 中修改 x 的合法方法?

最佳答案

标准在[dcl.type.cv]中说:

Except that any class member declared mutable […] can be modified, any attempt to modify […] a const object […] during its lifetime […] results in undefined behavior.

根据 [basic.life],也不可能通过过早结束对象的生命周期来定义它。 :

Creating a new object within the storage that a const complete object with […] automatic storage duration occupies, or within the storage that such a const object used to occupy before its lifetime ended, results in undefined behavior.

这意味着将 x - y 优化为零是有效的,因为任何修改 foo 中的 x 的尝试都会导致未定义的行为.

有趣的问题是,是否有理由不在现有编译器中执行此优化。考虑到 const 对象定义是 test2 的局部定义,并且在同一函数中使用了事实,因此支持符号插入等常见异常不适用于此处。

关于c++ - const 是否允许在此处进行(理论上的)优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55128512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com