Re: [問題] 請問pointer to reference有什麼好處呢?
看板C_and_CPP (C/C++)作者littleshan (我要加入劍道社!)時間16年前 (2009/03/27 19:43)推噓0(0推 0噓 0→)留言0則, 0人參與討論串2/2 (看更多)
※ 引述《allstarschh (allstars)》之銘言:
: 請問在中間那個function sharedInstance
: 為什麼不把code搬到 sharedInstanceInternal就好了
: 這樣就不用用到 reference to pointer了
: 因為用reference to pointer的話
: 有一邊free/delete 的話 另一個reference是不是就會有dangling refernece了
: 所以想來請教reference to pointer的好處 thanks
我覺得這是個很有趣的問題。
首先這是個典型的 singleton,除了基本的取得 shared instance 以外,
它還提供一個「檢查 instance 是否已被建立」的操作,也就是
sharedInstanceExists()。為了讓這個函式能正確運作,
sharedInstanceInternal() 必需要回傳 pointer (或 reference to pointer),
好讓 sharedInstanceExists() 檢查此 pointer 是否為 NULL。
原 po 的意思應該是指 sharedInstance() 與 SharedInstanceInternal()
其實是可以合併的,也就是如下的設計:
JSGlobalData.h:
class JSGlobalData {
public:
static JSGlobalData& sharedInstance();
static bool sharedInstanceExists();
private:
static JSGlobalData* shared_instance;
};
JSGlobalData.cpp:
JSGlobalData* JSGlobalData::shared_instance = NULL;
JSGlobalData& JSGlobalData::sharedInstance()
{
if(!shared_instance)
shared_instance = new JSGlobalData();
return *shared_instance;
}
bool JSGlobalData::sharedInstanceExists()
{
return shared_instance;
}
這樣的作法原則上 OK,不過原本的作法把 shared_instance 以 static
variable 的型式封裝在 sharedInstanceInternal() 當中,所以任何
JSGlobalData 的 member 要存取它時都必須先呼叫 sharedInstanceInternal(),
未來若要在存取 shared_instance 時添加額外的操作,會比較容易。
(修改 sharedInstanceInternal 即可)
最後,這個 singleton 顯然是不考慮 delete,配置給 shared instance
的記憶體空間會在程式結束後自動由 OS 回收。雖然這樣的設計並不是很好,
但對於 JSGlobalData 這樣的物件 (應該是存放 javascript global variable)
來說,由於不牽涉到其它資源,所以讓 OS 來回收記憶體是沒有問題的。
而既然不會有人 delete 它,那麼也沒有 dangling reference 的問題。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.121.117.19
※ 編輯: littleshan 來自: 59.121.117.19 (03/27 19:47)
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章