const在这里允许(理论上)优化吗? [英] Does const allow for (theoretical) optimization here?

查看:84
本文介绍了const在这里允许(理论上)优化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

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不允许xy进行更改,而在test1中的foo不能对其进行更改(例如,const_castconst 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?

推荐答案

该标准在

除了声明为mutable […]的任何类成员都可以修改之外,任何在其生存期[…]期间修改[…] const对象[…]的尝试都会导致未定义的行为.

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

根据

在具有[…]自动存储持续时间的const完整对象所占用的存储中,或在此类const对象在其生命周期结束前曾经被占用的存储中创建新对象会导致不确定的行为.

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的尝试都会导致不确定的行为.

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在这里允许(理论上)优化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆