我是一個Objective-C程序員,我最近開始C++,和我偶然到這個問題,在我的代碼的組織:C++對象保留?
std::list<char *> stuff = std::list<char *>();
thing *object = new thing(stuff);
凡stuff
將是我需要的對象我的班級生活(也就是說,直到它被破壞),如何避免失去它?
在Objective-C上,我可以簡單地在構造函數上調用-retain
。在C++?
我是一個Objective-C程序員,我最近開始C++,和我偶然到這個問題,在我的代碼的組織:C++對象保留?
std::list<char *> stuff = std::list<char *>();
thing *object = new thing(stuff);
凡stuff
將是我需要的對象我的班級生活(也就是說,直到它被破壞),如何避免失去它?
在Objective-C上,我可以簡單地在構造函數上調用-retain
。在C++?
,當你不需要他們不使用指針,並don't use owning raw pointers(除非你有一個非常好原因他們)。
使用自動存儲時間:
std::list<char> stuff;
thing object{stuff};
的thing
構造將採取std::list<char>
作爲它的參數:
#include <utility> // for std::move
class thing {
public:
explicit thing(std::list<char> stuff_) : stuff(std::move(stuff_)) {}
private:
std::list<char> stuff;
};
如果你做這樣的thing
析構函數會被調用當thing
超出範圍時,隱式調用stuff
的析構函數。許多good C++ books詳細解釋了這一點。
與Objective-C不同,C++使用RAII而不是引用計數。基本規則是:儘可能使用自動存儲持續時間,避免原始擁有指針,除非您有充足的理由,否則不要使用new
。
值得一提的是,這隻會使用C++ 11編譯器編譯,在GCC上您需要使用'g ++ -std = C++ 0x' – jozefg
或者如果其他人需要訪問同一個列表,並讓事物類引用列表而不是移動它。就目前而言,移動一個新構建的對象是沒有意義的。 –
通常的方法是在thing
構造函數stuff
複製或移動到thing
:
class thing {
public:
thing(std::list<char*> stuff) : stuff(std::move(stuff)) {}
private:
std::list<char *> stuff;
};
目前尚不清楚你將如何在你的榜樣使用stuff
,所以我要給你有幾個不同的選擇。
thing
存儲自己的副本stuff
。
在這種情況下,您的班級存儲std::list<char*>
類型的對象。
class thing
{
public:
thing(std::list<char*>& aList):m_list(alist){}
std::list<char*> m_list;
};
當你構建的stuff
thing
副本並儲存在類。當物體被破壞時,它會自動釋放m_list
。
thing
存儲對stuff
的弱引用。
你的課程將存儲一個指針(std::list<char*>* m_list
)或引用(std::list<char*>& m_list
)。 thing
將能夠以任何方式使用您的列表,但它不應該負責資源管理。如果列表的範圍小於thing
,那麼您將留下懸掛參考。
thing getThing()
{
std::list<char*> list1;
thing object1(list1);
return object1; //bad - list will be deallocated, object1 will have a hanging reference
}
thing
存儲共享指針stuff
。 這是目標C中最像retain
的方法。C++沒有自動引用計數。如果要存儲具有共享所有權的對象引用,則可以使用std::shared_ptr
。 thing
店std::shared_ptr<std::list<char*>> m_list
。
std::shared_ptr<std::list<char*>> stuff = std::make_shared<std::list<char*>>();
thing object(stuff); //reference count incremented, even if stuff is destroyed object will still hold a valid reference
如果'stuff'應該完全一樣長住爲'object'它也許,它應該是在對象,只是讓RAII採取其生命週期的服務。哦,ps,'new anthing'幾乎總是邪惡的,所以要小心 – jozefg
'thing'不會被銷燬,除非你明確地刪除它。我會推薦學習基礎知識,以獲得一個好的[C++書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 –
你會如何讓「東西」淡出現狀?你的意思是你在一個函數裏面創建它嗎? – Rubens