看板 C_and_CPP 關於我們 聯絡資訊
最近看到LLVM裡面的某一點coding standard讓我一直想不透 If a class is defined in a header file and has a vtable (either it has virtual methods or it derives from classes with virtual methods), it must always have at least one out-of-line virtual method in the class. Without this, the compiler will copy the vtable and RTTI into every .o file that #includes the header, bloating .o file sizes and increasing link times. 大意就是,在一個定義在header file裡的class有virtual method or 它繼承的base class有virtual method的話, 就必須至少定義一個virtual method 沒有的話compiler會copy vtable 和RTTI到每個有include這個header的.o檔 我的問題是,為什麼有一個virtual method compiler就不copy了? 所以vtable會放哪? 想知道整個故事是到底怎麼回事 有去看過more effective c++ item24 但是還是不太懂 只知道compiler copy是要解決vtable放哪的問題 請問有人知道嗎 感謝 ==== 知道了 http://www.angelfire.com/weird2/darkmoon/MEC/MI24_FR.HTM 裡面提到 A more common design is to employ a heuristic to determine which object file should contain the vtbl for a class. Usually this heuristic is as follows: a class's vtbl is generated in the object file containing the definition (i.e., the body) of the "first non-inline non-pure" virtual function in that class. If all virtual functions in a class are declared inline, the heuristic fails, and most heuristic-based implementations then generate a copy of the class's vtbl in every object file that uses it. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.230.112.113
johnny1972:你自己的翻譯漏了最重要的一個字 out-of-line 04/12 00:12
purpose:純猜測。假設有3個虛函式,當其中一個虛函式定義在 a.cpp 04/12 00:25
purpose:則 compiler 會覺得複製 vtable 可能不完整,就不複製了? 04/12 00:27
purpose:相對的,當3個虛函式都可以從標頭檔取得,則資訊必然充足 04/12 00:28
firose:應該是全都 inline 了所以要在這個編譯單元內找到 vtable 04/12 00:29
a9228097:out-of-line = non-inline, 我還自動忽略那個字.. 04/12 00:34
※ 編輯: a9228097 來自: 61.230.112.113 (04/12 00:38)
purpose:所以他是指,從一開始 vtbl 就只想放在一處儲存而已 04/12 00:47
purpose:只是挑選策略失敗,就乾脆海派點,每個有用到的地方都塞 04/12 00:48
tinlans:我 virtual function 從來不 inline,這東西能 inline 嗎? 04/12 23:37
tinlans:所以當初我在 LLVM 看到那條完全無視,感覺是說廢話。 04/12 23:39
a9228097:我是看到source裡有"virtual method anchor"才看到這個 04/13 00:17
a9228097:規定, 才疑惑為啥要這樣規定 04/13 00:18