c++ - 即使没有明确定义为内联,一个非常短的函数也可以内联吗?

标签 c++ c inline-functions

我事先知道,在用 C 或 C++ 编写程序时,即使我将函数声明为“内联”,编译器也可以随意忽略它并决定不在每次(或任何)调用时扩展它。

反之亦然吗?也就是说,如果编译器认为这样做会带来性能提升,那么编译器是否可以自动内联未定义为内联的非常短的函数?

另外两个子问题:此行为是否在 ANSI 标准的某处定义?在这方面,C 与 C++ 是不同的,还是它们的行为相同?

最佳答案

inline 对于函数是否会被编译器内联没有约束力。这本来就是它打算做的。但从那时起,人们意识到函数是否值得内联取决于函数本身和调用站点,最好由编译器来决定。

来自 https://en.cppreference.com/w/cpp/language/inline :

Since this meaning of the keyword inline is non-binding, compilers are free to use inline substitution for any function that's not marked inline, and are free to generate function calls to any function marked inline. Those optimization choices do not change the rules regarding multiple definitions and shared statics listed above.

编辑:因为你也要求 C,来自 https://en.cppreference.com/w/c/language/inline :

The intent of the inline specifier is to serve as a hint for the compiler to perform optimizations, such as function inlining, which require the definition of a function to be visible at the call site. The compilers can (and usually do) ignore presence or absence of the inline specifier for the purpose of optimization.

关于c++ - 即使没有明确定义为内联,一个非常短的函数也可以内联吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53503270/

相关文章:

c++ - 检测可移动驱动器(例如 USB 闪存驱动器)C/C++

c - 询问 mpi mpich 中的 MPI_Reduce 和 MPI_Bcast

c - 传递给 Linux C 内联函数的参数

编译器/链接错误: Freedup

c++ - 这个 boost::lambda 使用有什么问题?

c++ - 在哪里放置 using namespace std;

c++ - 在 C++ 中使用您自己的 Matrix 类进行 OpenGL 对象旋转

c++ - 我可以强制 C++ 类使用最小空间量进行编译吗?

c - 段错误 : 11 while copying one array to another

c++ - GCC 编译器内联的深度