問題描述
根據 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 itinline
if it's called only from that TU. Then it probably makes no difference whether it is markedinline
or not, but you could mark itinline
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++ 成員函數中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!