c++内联函数
我对如何在 C++ 中执行内联函数感到困惑......
让我们说这个函数。如何将其转换为内联函数
int maximum( int x, int y, int z )
{
int max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}
i'm confused about how to do inline functions in C++....
lets say this function. how would it be turned to an inline function
int maximum( int x, int y, int z )
{
int max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为了将其变成内联函数,您需要做两件事:
inline
将其声明为内联函数。In order to turn it into an inline function you need to do two things:
inline
.正如其他人所说,您可以使用
inline
关键字告诉编译器您希望内联函数。但inline
关键字只是编译器提示。如果编译器愿意或需要的话,它可以并且将会选择忽略您的请求。另一种方法是让你的函数成为函数模板,它通常会被内联吹出:
As others have said, you can use the
inline
keyword to tell the compiler you want your function inlined. But theinline
keyword is just a compiler hint. The compiler can and will chose to ignore your request if it wants or needs to.An alternative is to make your function a function template, which will often be blown out inline:
将尼尔斯的答案作为实际答案发布:
To post Neils answer as an actual answer:
如果该函数定义出现在
class {}
定义中,则它已经自动内联。否则,正如其他人所说,将
inline
放在前面。If that function definition appears inside a
class {}
definition, then it is automatically inline already.Otherwise, as others say, put
inline
infront.要使函数内联,请使用 inline 关键字:
如果函数是类/结构的成员,则只需在类内部(而不是在类外部)定义它即可使其内联。
假设您有这样的调用:
编译器可能会将调用扩展为:
调用函数会产生一些开销,因此内联函数为您提供了函数的便利性以及 C 宏的性能。但这并不是说您应该始终使用它们,在大多数情况下,编译器更擅长决定何时需要这样的优化,甚至可能不会满足您的请求。
您可以在 C++ FAQ Lite 和这个 GotW
To make the function inline use the inline keyword:
If the function is a member of a class/struct then simply defining it inside the class (as apposed to outside it) makes it inline.
Say you have the call:
The compiler might expands the call to something like:
There's some overhead to calling a function, so inline functions give you the convenience of functions along with the performance of C macros. But that's not to say you should always use them, in most cases the compiler is better at deciding when optimizations like this are needed and might not even honor your request.
You can read more about inline functions and how (and when) to use them at C++ FAQ Lite and this GotW
inline
只是告诉编译器您希望将函数代码复制到引用的任何地方,它使代码更快一点(没有函数调用开销)但更大(代码被复制)。 此页面更深入。inline
just tells the compiler that you want the function code copied everywhere it is refernece, it makes the code a bit faster (no function call overhead) but bigger (the code is copied). This page is more in depth.