C++ 中是否内联静态 constexpr 变量?
Are static constexpr variables inlined in C++?
让我们在 C++14 中编写以下代码:
using namespace std;
void foo(int a)
{
cout << a;
}
int main()
{
//version1
foo(13);
//version2
static constexpr int tmp = 13;
foo(tmp);
return 0;
}
编译器是否会自动将版本 2 优化为版本 1,以便内联 static constexpr
变量(在 C 中的处理器期间处理诸如定义之类的东西)?如果是这样,这方面的规则是什么?如果它只是 constexpr
或 static const
是否仍会内联?
来自http://eel.is/c++draft/dcl.constexpr#1.sentence-3
A function or static data member declared with the constexpr or consteval specifier is implicitly an inline function or variable.
编译器在 "as if" 规则下有很大的自由度,可以根据自己的喜好进行优化。鉴于您发布的代码相当简单,即使您从定义中删除 static constexpr
,编译器也能优化 "version 2" 。编译器可以看到您没有在初始化和使用之间更改变量的值,并且可以看到 use 是编译时值,因此它可以使用初始化值调用该函数。如果它能看到定义,甚至可以优化函数本身。
任何特定的编译器是否会优化掉某些代码取决于编译器设置和代码的特定细节(特别是在值的创建和使用之间进行干预的代码)。这个没有"rules"。
让我们在 C++14 中编写以下代码:
using namespace std;
void foo(int a)
{
cout << a;
}
int main()
{
//version1
foo(13);
//version2
static constexpr int tmp = 13;
foo(tmp);
return 0;
}
编译器是否会自动将版本 2 优化为版本 1,以便内联 static constexpr
变量(在 C 中的处理器期间处理诸如定义之类的东西)?如果是这样,这方面的规则是什么?如果它只是 constexpr
或 static const
是否仍会内联?
来自http://eel.is/c++draft/dcl.constexpr#1.sentence-3
A function or static data member declared with the constexpr or consteval specifier is implicitly an inline function or variable.
编译器在 "as if" 规则下有很大的自由度,可以根据自己的喜好进行优化。鉴于您发布的代码相当简单,即使您从定义中删除 static constexpr
,编译器也能优化 "version 2" 。编译器可以看到您没有在初始化和使用之间更改变量的值,并且可以看到 use 是编译时值,因此它可以使用初始化值调用该函数。如果它能看到定义,甚至可以优化函数本身。
任何特定的编译器是否会优化掉某些代码取决于编译器设置和代码的特定细节(特别是在值的创建和使用之间进行干预的代码)。这个没有"rules"。