Leo*_*aar 19 c++ const constexpr c++11 c++14
例如:
constexpr int g() { return 30; }
constexpr int f()
{
// Can we omit const?
const int x = g();
const int y = 10;
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
有没有必要在constexpr
函数中声明局部变量const
?
局部变量的constexpr
函数不等于没有const
局部变量的函数吗?const
换句话说,constexpr
函数是否强加(暗示)const
它的局部变量?
小智 23
const
在非constexpr
函数中声明变量的相同参数也适用于constexpr
函数:
const
记录了它永远不会被更改的事实.在某些情况下,这可能有助于使函数更具可读性.const
会影响重载决策,并且可能使h(x)
解决h
不同,这取决于是否x
是const
.当然,正如相反的方向,已经在评论中提到:
即使在constexpr
函数中,也可以改变局部变量.如果这些变量随后被const
更改,则不再接受尝试更改它们.
How*_*ant 16
在这个特定的例子中的局部变量将最好的宣布constexpr
,没有const
,因为他们可以在编译时计算:
constexpr int g() { return 30; }
constexpr int f()
{
constexpr int x = g();
constexpr int y = 10;
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
当f()
被称为在运行时,没有constexpr
对x
和y
,(有或没有const
上x
和y
)你给编译器初始化选项x
,并y
在运行时,而不是编译时间.使用constexpr
on x
和y
,编译器应计算x
并y
在编译时,即使f()
在运行时执行.
但是,在不同的功能中,constexpr
不能总是使用.例如,如果f()
并g()
采取参数:
constexpr int g(int z) { return z+30; }
constexpr int f(int z)
{
const int x = g(z);
constexpr int y = 10;
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
现在x
无法标记constexpr
因为z
可能不是编译时常量,并且目前无法将其标记为此类.所以在这种情况下,标记x
const
是你能做的最好的.