精華區beta Programming 關於我們 聯絡資訊
※ 引述《Oscar0121 (java新手)》之銘言: : ※ 引述《tinlans.bbs@whshs.cs.nccu.edu.tw (汀)》之銘言: : : class member function pointer, : : 這是 C++ 特有的 function pointer, : : size 在大部分的 C++ 環境都是一般指標的兩倍, : : 這個 overhead 也算是 C++ 的常識之一, : : 不過很多教授不知道... 其實通常不一定是這麼回事,也未必有 overhead 在 inline 的時候可以避免 overhead,且就算沒 inline 不見得比較慢 以下舉相當常用的 Visual C++ 為例 member function 和 一般的 static function 其 pointer 大小完全一樣 差別只在 calling convention,一個是 C 的 calling convention 另一個是 this call,也就是 call 的時候把 this pointer 放入 ECX register 其實這效果跟 fast call 相當類似,function pointer 本身和 static function 無異 void gtk_window_set_title(register GtkWindow* window, gchar* title); void GtkWindow::set_title(gchar* title); 上面兩行實際執行的效果和 overhead 基本上完全一樣,而早期的 C 不能 inline 所以 C++ 有時不但不會比較慢,而且經常能略勝 C 一籌 一般來說 Getter 和 Setter function 都會寫成 inline,無 overhead C++ 的 function 會有 overhead 的地方主要在 virtual function, 而非所有 member function 都會,事實上大多 member function 和 C 沒差 以上雖然沒有明文規範,但是編譯器基本上不會選擇用比較有 overhead 的方式實做 這些東西教授不知道很正常,換一個好的演算法往往勝過你省下上千個 overhead 研究演算法的人不需計較這種實做細節,那對他們沒有意義。 : : #include <iostream> : : using namespace std; : : class X { : : void foo() { } : : }; : : int main() : : { : : void (X::*ptr)(void); : : cout << sizeof(ptr) << endl; : : return 0; : : } : tinlan大大您好 感謝您為我們解惑 : 版上也常拜讀您的文章 受益不少^^ : 但是此例小弟實驗結果 怎麼都還是4 byte呢 : 編譯環境 VC6 console mode : 哪裡有問題呢?編譯環境沒設定好嗎 : #include <iostream> : using namespace std; : class X{ : void foo(void){} : }; : int main() : { : void (X::*ptr)(void); : cout<<sizeof(ptr)<<endl; : int* pt=new int(6); //一般pointer : cout<<sizeof(pt)<<endl; : return 0; : } : 兩者皆輸出 4 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.129.67.69