是“内联"吗?隐含在类定义中定义的 C++ 成员

Is quot;inlinequot; implicit in C++ member functions defined in class definition(是“内联吗?隐含在类定义中定义的 C++ 成员函数中)

本文介绍了是“内联"吗?隐含在类定义中定义的 C++ 成员函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 C++ 规范,以下两个类是否等价定义?

According to the C++ specification, are the following two classes equivalently defined?

class A
{
   void f()
   {
   }
};

class B
{
   inline void f()
   {
   }
};

即,将内联"限定符放在类定义中定义的此类成员函数上是否完全多余?

i.e., is putting the "inline" qualifier on such member function defined in the class definition completely redundant?

后续问题:假设它是多余的,对于代码风格,保留内联"标签是否明智,因此未来的开发人员意识到应该内联该函数,并且不会删除其他地方的定义并删除内联?

Followon question: Assuming it is redundant, for code style, would it be sensible to keep the "inline" tag, so a future developer realises that function should be inlined, and does not remove the definition somewhere else and remove the inlining?

谢谢:)

推荐答案

它们是等价的类定义,除了单一定义规则的用途.所以标准不保证你可以用一个类定义编译一个 TU(翻译单元),用另一个编译一个不同的 TU,然后将它们链接在一起.我怀疑这是否会在真正的实现中失败,但这就是标准所说的.

They're equivalent class definitions except for the purposes of the One Definition Rule. So the standard does not guarantee that you can compile one TU (translation unit) with one class definition and a different TU with the other, and then link them together. I doubt that this would ever actually fail on a real implementation, but that's what the standard says.

inline 关键字几乎与内联无关.这是关于在不同的 TU 中是否允许函数的多个相同定义.如果有人把函数定义移到别处,那么他们应该根据以下基础决定是否标记它inline:

The inline keyword has approximately nothing to do with inlining. It's about whether multiple identical definitions of the function are permitted in different TUs. If someone moves the function definition elsewhere, then they should decide whether to mark it inline on the following basis:

  • 如果它在该类的 .cpp 文件中,那么如果它仅从该 TU 调用,则将其标记为 inline 是有效的.那么它是否标记为 inline 可能没有区别,但是如果您认为编译器会注意您的内容,则可以将其标记为 inline 作为编译器提示想要.

  • If it is in a .cpp file for that class, then it's valid to mark it inline if it's called only from that TU. Then it probably makes no difference whether it is marked inline or not, but you could mark it inline as a compiler hint if you think the compiler will pay any attention to what you want.

如果它仍在头文件中,则必须将其标记为inline,否则在链接使用该头文件的不同 TU 时会出现多个定义错误.

If it is still in the header file, then it must be marked inline, or else you'll get multiple definition errors when linking different TUs that use the header.

假设移动函数的人知道那些东西,我认为他们不需要在类定义中提醒.如果他们不知道这些事情,那么他们可能无法移动该函数,但对他们来说,使用 inline 关键字来移动它会更安全.

Assuming that the person moving the function knows those things, I don't think they need a reminder in the class definition. If they don't know those things, then they probably have no business moving the function, but it would be safer for them to have an inline keyword to move with it.

这篇关于是“内联"吗?隐含在类定义中定义的 C++ 成员函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:是“内联"吗?隐含在类定义中定义的 C++ 成员

基础教程推荐