[問題] 請問reference to pointer有什麼好處呢?

看板C_and_CPP (C/C++)作者 (allstars)時間16年前 (2009/03/27 18:03), 編輯推噓1(106)
留言7則, 5人參與, 最新討論串1/1
我在看WebKit的code時 發現某段code有用reference to pointer bool JSGlobalData::sharedInstanceExists() { return sharedInstanceInternal(); } JSGlobalData& JSGlobalData::sharedInstance() { JSGlobalData*& instance = sharedInstanceInternal(); if (!instance) { instance = new JSGlobalData(true); } return *instance; } JSGlobalData*& JSGlobalData::sharedInstanceInternal() { ASSERT(JSLock::currentThreadIsHoldingLock()); static JSGlobalData* sharedInstance; return sharedInstance; } 請問在中間那個function sharedInstance 為什麼不把code搬到 sharedInstanceInternal就好了 這樣就不用用到 reference to pointer了 因為用reference to pointer的話 有一邊free/delete 的話 另一個reference是不是就會有dangling refernece了 所以想來請教reference to pointer的好處 thanks -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.67.242.96

03/27 18:46, , 1F
我想這就是singleton寫法的習慣吧 你只需要透過某函數
03/27 18:46, 1F

03/27 18:47, , 2F
就可以取得 這class裡面唯一的資源~
03/27 18:47, 2F

03/27 19:07, , 3F
sharedInstanceInternal() 會吐出一個pointer, 你要怎麼讓
03/27 19:07, 3F

03/27 19:59, , 4F
被標題誤導了...
03/27 19:59, 4F

03/27 22:49, , 5F
sorry 我把標題打錯了 修正一下
03/27 22:49, 5F

03/28 00:26, , 6F
class作者把指標藏到函式裡 確保使用指標前必做安全檢查
03/28 00:26, 6F

03/28 00:27, , 7F
藏進去的話 回傳就只能是reference to pointer
03/28 00:27, 7F
文章代碼(AID): #19pAI7mc (C_and_CPP)
文章代碼(AID): #19pAI7mc (C_and_CPP)