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

Is function defined in class always inline?

根据某些书籍,class 中定义的函数(以及 header 中的定义)始终是内联的。真的吗?

我们如何使用测试应用创建这样的场景?

是的,确实如此,class中定义的成员函数被隐式声明为内联。但是 inline 只是你给编译器的一个建议。编译器可以忽略它。

如果您想了解不同情况下会发生什么,您可以阅读汇编程序

class 定义中定义的函数被隐式标记为 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. [..]

这与说它们将被内联是不一样的。

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. 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.

然而,如今,您的编译器将根据其自身的指标来决定是否物理内联函数,而不是基于 inline 关键字的存在与否(因为,坦率地说,如今编译器最清楚)。

我不知道 "test app" 你在想什么,但是代码中的一个例子非常简单:

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