内联函数机制 [英] Inline functions mechanism

查看:206
本文介绍了内联函数机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道内联函数不使用堆栈来复制参数,但它只是替换了函数的主体,无论它被调用。



考虑这两个函数:

  inline void add(int a){
a ++;
} //什么都不做,a不会被改变
inline void add(int& a){
a ++;
} //更改
的值

如果堆栈不用于发送参数,编译器如何知道变量是否将被修改?

inline 关键字有两个关键效果。一个效果是,它的实现提示,在调用点的函数体的在线替换被优先于通常的函数调用机制。这种用法是一个提示,不是因为在调用点

不需要执行该在线替换。



另一个主要效果是如何它修改一个定义规则。根据ODR,程序必须只包含在程序中使用的任何给定非内联函数的一个定义。这不适用于内联函数,因为内联函数应在其使用odr的每个转换单元中定义...。在一百个不同的翻译单元中使用相同的内联函数,链接器将面对函数的一百个定义。这不是一个问题,因为相同函数的多个实现...在每种情况下应该有完全相同的定义。一种方法来看:这里只有一个定义;它看起来像是链接器的一大堆。



注意:所有引用的材料都是从C ++ 11标准的第7.1.2节。


I know that an inline function does not use the stack for copying the parameters but it just replaces the body of the function wherever it is called.

Consider these two functions:

inline void add(int a) {
   a++; 
} // does nothing, a won't be changed
inline void add(int &a) {
   a++; 
} // changes the value of a

If the stack is not used for sending the parameters, how does the compiler know if a variable will be modified or not? What does the code looks like after replacing the calls of these two functions?

解决方案

The inline keyword has two key effects. One effect is that it is a hint to the implementation that "inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism." This usage is a hint, not a mandate, because "an implementation is not required to perform this inline substitution at the point of call".

The other principal effect is how it modifies the one definition rule. Per the ODR, a program must contain exactly one definition of any given non-inline function that is odr-used in the program. That doesn't quite work with an inline function because "An inline function shall be defined in every translation unit in which it is odr-used ...". Use the same inline function in one hundred different translation units and the linker will be confronted with one hundred definitions of the function. This isn't a problem because those multiple implementations of the same function "... shall have exactly the same definition in every case." One way to look at this: There still is only one definition; it just looks like there are a whole bunch to the linker.

Note: All quoted material are from section 7.1.2 of the C++11 standard.

这篇关于内联函数机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆