看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《neville123 (nk)》之銘言: : virtual void *emitFunctionStub(const Function* F, void *Target, : JITCodeEmitter &JCE) { : assert(0 && "This target doesn't implement emitFunctionStub!"); : return 0; : } : 最近在看code的時候, 覺得這段很奇怪, 想請問為什麼function body裡面什麼都沒做呢? : 因為他傳了一些參數進來不是嗎? 另外也想問一下 assert以字串當作參數是什麼用法呢? : 謝謝~ 1. 這裡的關鍵字是 virtual 也就是說這個 class 的設計者期望對它的使用是繼承下來 把這個函式實作起來才拿來用 因此寫成這樣 當繼承它的人沒有實作時就會噴出這個錯誤訊息出來 2. assert 這裡其實不是拿字串當作參數 注意到前面有個 0 && 你可以當成 false && 因此這個 assert 一定失敗 也就是在 debug build 當中執行到這一行就會炸給你看 之所以要寫個字串在那裡的原因是 assert 失敗時會吐出你是什麼式子判斷失敗 (而且是原文照搬; 內部使用的技巧我在 #1EV01Wpd 這篇說過, 這裡表過不提) 因此當在這裡炸掉時你就會炸掉的訊息當中看到類似 assert failed: 0 && "This target doesn't implement emitFunctionStub!" 這樣的文字 於是你就可以很清楚問題出在這裡 3. 所以雖然我個人偏好把這個函式寫成 pure virtual 強制使用者實作 (以此例來說就是 virtual void *emitFunctionStub(const Function* F, void *Target, JITCodeEmitter &JCE) = 0; 寫成這個樣子, 而且這樣當沒實作的時候一編譯就會炸掉, 不用到執行) 但這種寫法也不失為是一個提醒使用者的方式就是了 -- 'Oh, Harry, don't you see?' Hermione breathed. 'If she could have done one thing to make absolutely sure that every single person in this school will read your interview, it was banning it!' ---'Harry Potter and the order of the phoenix', P513 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.230.62
neville123:也就是說這個function只是種概念 實際做法必須讓使用 01/21 11:33
neville123:者自己來實作是吧?! 01/21 11:33
diabloevagto:你可以查一下oo的interface會更清楚 01/21 11:46
neville123:可以請問一下樓上關鍵字嗎? 01/21 12:49
final01:XD 就 oo interface阿 01/21 13:15
neville123:XD" 謝謝幾位 01/21 13:47
loveme00835:我覺得寫這段程式碼的人根本不知道有 pure virtual 01/21 15:58
loveme00835:function, 或者本來應該要實作的東西他忘了 01/21 15:59
hilorrk:我一開始看到的第一個想法是他只是還沒寫上去XD 01/21 16:02
applecool:所以如果要印出訊息就是 assert(0 && "...") ? 01/21 16:26
applecool:還是 assert(!"...") 也可以嗎?? 01/21 16:27
applecool:實驗後者好像是對的 01/21 16:27
tropical72:@applecool: 如果你確定 "...." 不是傳回NULL才可如此. 01/21 17:19
uranusjr:而且 0 && 應該會速度快一點? (short-circuit 的關係) 01/21 18:42
fengchu:實作Composite Pattern時可能用到這種寫法,例如Folder 01/21 20:03
fengchu:和File同樣繼承Entry,但File沒有Entry中Folder所需的 01/21 20:05
fengchu:getChildren(),因此讓留一個預設實作讓File.getChildren( 01/21 20:06
fengchu:)自爆,類似Java擲出OperationNotSupportedException 01/21 20:07
loveme00835:樓上說的不是問題,可以 ret this等等,只是手法不同 01/21 20:44
applecool:Thank you! 01/23 01:36
LifePattern:@loveme00835 他不寫成pure virtual是想留下彈性 01/23 19:23
LifePattern:我不會呼叫到 所以不實做很合理阿XD 01/23 19:24