我们可以在constexpr函数的局部变量上省略const吗? [英] Can we omit const on local variables in constexpr functions?

查看:79
本文介绍了我们可以在constexpr函数的局部变量上省略const吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

constexpr int g() { return 30; }    

constexpr int f()
{
    // Can we omit const?
    const int x = g();
    const int y = 10;

    return x + y;
}

使用 const constexpr 函数中声明局部变量吗?

Is there any point to ever declare local variables in a constexpr function with const?

具有 const 局部变量的 constexpr 函数是否与没有 const 的变量具有等效的功能?

Aren't constexpr functions with const local variables equivalent to those with no const?

换句话说,函数上的 constexpr 是否将 const 强加(暗示) const 在其局部变量上?

In other words, does constexpr on a function impose (imply) const on its local variables?

推荐答案

在非 constexpr 函数中与 const 声明变量的参数相同,也适用于constexpr 函数:

The same arguments for declaring variables as const in non-constexpr functions also apply to constexpr functions:

  • 声明变量 const 记录了它永远不会被更改的事实.在某些情况下,这可能有助于使该功能更具可读性.
  • 声明变量 const 将影响重载解析,并且可能使 h(x)根据 x const .
  • Declaring a variable const documents the fact that it won't ever be changed. This may in some instances help make the function more readable.
  • Declaring a variable const affects overload resolution, and may make h(x) resolve h differently depending on whether x is const.

当然,朝相反的方向,正如已经在评论中提到的那样:

Of course, in the opposite direction, as mentioned in comments already:

即使在 constexpr 函数中,局部变量也可能会更改.如果随后更改了这些变量,使它们成为 const ,则将不再接受尝试更改它们的尝试.

Even in constexpr functions, local variables may be changed. If those variables are then changed so that they are const, attempts to change them will no longer be accepted.

这篇关于我们可以在constexpr函数的局部变量上省略const吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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