C++ constexpr 是否意味着内联?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14391272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does constexpr imply inline?
提问by Vincent
Consider the following inlined function :
考虑以下内联函数:
// Inline specifier version
#include<iostream>
#include<cstdlib>
inline int f(const int x);
inline int f(const int x)
{
return 2*x;
}
int main(int argc, char* argv[])
{
return f(std::atoi(argv[1]));
}
and the constexpr equivalent version :
和 constexpr 等效版本:
// Constexpr specifier version
#include<iostream>
#include<cstdlib>
constexpr int f(const int x);
constexpr int f(const int x)
{
return 2*x;
}
int main(int argc, char* argv[])
{
return f(std::atoi(argv[1]));
}
My question is : does the constexpr
specifier imply the inline
specifier in the sense that if a non-constant argument is passed to a constexpr
function, the compiler will try to inline
the function as if the inline
specifier was put in its declaration ?
我的问题是:从某种意义上说,constexpr
说明符是否暗示说明inline
符,如果将非常量参数传递给constexpr
函数,编译器将尝试使用inline
该函数,就像将inline
说明符放在其声明中一样?
Does the C++11 standard guarantee that ?
C++11 标准是否保证?
回答by Jerry Coffin
Yes ([dcl.constexpr], §7.1.5/2 in the C++11 standard): "constexpr functions and constexpr constructors are implicitly inline (7.1.2)."
是([dcl.constexpr],C++11 标准中的第 7.1.5/2 节):“constexpr 函数和 constexpr 构造函数是隐式内联的(7.1.2)。”
Note, however, that the inline
specifier really has verylittle (if any) effect upon whether a compiler is likely to expand a function inline or not. It does, however, affect the one definition rule, and from that perspective, the compiler is required to follow the same rules for a constexpr
function as an inline
function.
但是请注意,该inline
说明符确实有非常少(如果有的话)的影响在一个编译器是否有可能扩大一个内联函数或没有。然而,它确实会影响一个定义规则,从这个角度来看,编译器需要遵循与constexpr
函数相同的函数规则inline
。
I should also add that regardless of constexpr
implying inline
, the rules for constexpr
functions in C++11 required them to be simple enough that they were often good candidates for inline expansion (the primary exception being those that are recursive). Since then, however, the rules have gotten progressively looser, so constexpr
can be applied to substantially larger, more complex functions.
我还应该补充一点,不管constexpr
暗示如何,C++11 中的函数inline
规则constexpr
要求它们足够简单,以至于它们通常是内联扩展的良好候选者(主要的例外是那些递归的)。然而,从那时起,规则变得越来越松散,因此constexpr
可以应用于更大、更复杂的功能。