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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:18:34  来源:igfitidea点击:

Does constexpr imply inline?

c++c++11inlinestandards-complianceconstexpr

提问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 constexprspecifier imply the inlinespecifier in the sense that if a non-constant argument is passed to a constexprfunction, the compiler will try to inlinethe function as if the inlinespecifier 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 inlinespecifier 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 constexprfunction as an inlinefunction.

但是请注意,该inline说明符确实有非常少(如果有的话)的影响在一个编译器是否有可能扩大一个内联函数或没有。然而,它确实会影响一个定义规则,从这个角度来看,编译器需要遵循与constexpr函数相同的函数规则inline

I should also add that regardless of constexprimplying inline, the rules for constexprfunctions 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 constexprcan be applied to substantially larger, more complex functions.

我还应该补充一点,不管constexpr暗示如何,C++11 中的函数inline规则constexpr要求它们足够简单,以至于它们通常是内联扩展的良好候选者(主要的例外是那些递归的)。然而,从那时起,规则变得越来越松散,因此constexpr可以应用于更大、更复杂的功能。