gpt4 book ai didi

c++ - 类中定义的函数是否总是内联的?

转载 作者:太空狗 更新时间:2023-10-29 20:11:42 24 4
gpt4 key购买 nike

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

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

最佳答案

在类定义中定义的函数被隐式标记为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 关键字(因为,坦率地说,如今编译器最清楚)。

我不知道您在想什么“测试应用”,但是代码中的一个示例非常简单:

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

关于c++ - 类中定义的函数是否总是内联的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com