在头部定义的C ++类方法总是内联吗? [英] Are C++ class methods defined in the header always inlined?

查看:115
本文介绍了在头部定义的C ++类方法总是内联吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


编辑:我已经恢复了原来的标题,但我真正应该问的是:'C ++链接器如何处理已经在多个对象文件'

Edit: I've restored the original title but really what I should have asked was this: 'How do C++ linkers handle class methods which have been defined in multiple object files'

说我有一个C ++类,在标题中定义如下:

Say I have a C++ class defined in a header along these lines:

class Klass
{
    int Obnoxiously_Large_Method()
    {
        //many thousands of lines of code here
    }
}



如果我编译了一些在多个位置使用'Obnoxiously_Large_Method'的C ++代码,将生成的目标文件总是内联Obnoxiously_Large_Method的代码,或者它将优化大小(例如,当使用g ++ -Os)并创建一个'Obnoxiously_Large_Method'的单个实例,并像普通函数一样使用它,如果是这样,链接器如何解决已实例化相同功能的其他目标文件之间的冲突?是否有一些奥秘C ++命名空间Juju,它保持方法的单独对象实例彼此冲突?

If I compile some C++ code which uses 'Obnoxiously_Large_Method' in several locations, will the resulting object file always inline the code for 'Obnoxiously_Large_Method' or will it optimise for size (for example, when using g++ -Os) and create a single instance of 'Obnoxiously_Large_Method' and use it like a normal function?, if so, how do linkers resolve the collisions between other object files which have instantiated the same function?. Is there some arcane C++ namespace Juju which keeps the separate object instances of method from colliding with each other?

推荐答案


7.1.2函数说明符

7.1.2 Function specifiers

带有内联说明符的函数声明(8.3.5,9.3,11.4)
声明一个内联函数。内联说明符指示
实现,在
调用点处的函数体的内联替换被优先于通常的函数调用机制。
在调用点处执行这个内联替换
不需要实现;但是,即使这个内联替换是
省略,7.1.2定义的内联函数的其他规则仍然应该遵守

A function declaration (8.3.5, 9.3, 11.4) with an inline specifier declares an inline function. The inline specifier indicates 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. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.

因此,编译器不需要实际内联任何函数。

So, the compiler is not required to actually 'inline' any function.

但是,标准还说,


带有外部链接的内联函数在所有翻译单元中应具有相同的地址。

An inline function with external linkage shall have the same address in all translation units.

成员函数通常有外部链接(一个例外是当成员函数属于'local'类时),因此内联函数必须有一个唯一的地址。在这种情况下,编译器将安排链接器丢弃除函数的非内联副本的所有实例,并将函数的所有地址引用都保存到保留的函数。

Member functions normally have external linkage (one exception is when the member function belongs to a 'local' class), so inline functions must have a unique address for cases where the address of the function is taken. In this case, the compiler will arrange for the linker to throw away all but one instance of a non-inlined copy of the function and fix-up all address references to the function to be to the one that's kept.

这篇关于在头部定义的C ++类方法总是内联吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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