简体   繁体   English

类中定义的函数是否始终内联?

[英]Is function defined in class always inline?

As per some of the books, function defined(along with definition in header) in class are always inline. 根据一些书籍,类中定义的函数(以及标题中的定义)始终是内联的。 Is that true? 真的吗?

How we can create such scenario using test app? 我们如何使用测试应用程序创建此类场景?

Functions defined within the class definition are implicitly marked inline . 在类定义中定义的函数是inline隐式标记的。

[C++11: 9.3/2]: A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition. [C++11: 9.3/2]:成员函数可以在其类定义中定义(8.4),在这种情况下,它是内联成员函数(7.1.2),或者可以在其类定义之外定义如果已经声明但未在其类定义中定义。 [..] [..]

That is not the same as saying that they will be inlined. 这与他们将被内联的说法不同。

The inline keyword has implications for storage duration and linkage requirements, and these must be abided by. inline关键字对存储持续时间和链接要求有影响, 必须遵守这些要求。

[C++11: 7.1.2/2]: A function declaration (8.3.5, 9.3, 11.3) with an inline specifier declares an inline function . [C++11: 7.1.2/2]:带有inline说明符的函数声明(8.3.5,9.3,11.3)声明了一个内联函数 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. 但是,即使省略了这种内联替换,仍应遵守7.1.2定义的内联函数的其他规则。

However, nowadays, your compiler will make the decision on whether to physically inline a function based on its own metrics, not based on the presence or absence of the inline keyword (because, nowadays, frankly the compiler knows best). 但是,现在,您的编译器将决定是否基于其自身的度量来物理内联函数,而不是基于inline关键字的存在与否(因为,现在,坦率地说编译器最了解)。

I have no idea what "test app" you have in mind, but an example of this in code is very simple: 我不知道你有什么“测试应用程序”,但代码中的一个例子非常简单:

struct T
{
   void foo() {}  // implicitly `inline`
};

Yes, it is true, the member functions defined in the class are implicitly declared inline. 是的,确实,类中定义的成员函数是内联隐式声明的。 But inline is only a suggestion you give to the compiler. 但是inline只是你给编译器的一个建议。 The compiler could ignore it. 编译器可以忽略它。

If you want to see what happen with different scenarios you could read the assembler 如果您想了解不同场景会发生什么,您可以阅读汇编程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM