是否不允许编译器假定const-ref参数将保持const? [英] Are compilers not allowed to assume const-ref parameters will stay const?

查看:62
本文介绍了是否不允许编译器假定const-ref参数将保持const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

https:// godbolt。 org / g / 5eUkrx

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

似乎 f对其参数进行了变异应该是UB,因此编译器应该允许它不会发生,并相应地进行优化。然而,这两个函数将产生不同的汇编。

It seems like "f" mutating its argument should be UB, and therefore compilers should be allowed to assume it doesn't happen and optimize accordingly. Yet these two functions will produce different assembly.

我没有该标准的副本。

I don't have a copy of the standard. Is this not guaranteed?

推荐答案

根据标准,将指针指向const的指针转换为指针指向-在C ++中使用非常量,然后对其进行修改(尽管这很令人困惑),只要指针所指向的值未声明为 const 。实际上,C ++提供了一个进行此类转换的关键字 const_cast

It's perfectly fine according to the standard to cast a pointer-to-const to pointer-to-non-const in C++ and then modify it (albeit it is confusing), as long the value the pointer points to wasn't declared as const. In fact, C++ provides a keyword to do such a cast, const_cast.

例如,这很好。

int a = 2;
const int* b = &a;
*const_cast<int*>(b) = 4;

但这并不是指针指向的存储位置 const

But this isn't as a memory location to which pointer points to is const.

const int a = 2;
const int* b = &a;
*const_cast<int*>(b) = 4;

在您的示例中,编译器必须假设被调用的函数可以做到这一点,因为它对此一无所知,并为这种情况做准备。

Compiler in your example has to assume that a called function could possibly do that as it knows nothing about it, and prepare for such a situation.

这篇关于是否不允许编译器假定const-ref参数将保持const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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