2011-03-22 61 views
0

我在我的應用程序設計中使用shared_ptr,並且我有越來越多的對象變成堆分配而不是堆棧上的簡單對象(或更復雜對象的聚集)的趨勢。
而不是簡單的(但有可能Foo :: bar會在更復雜的情況下變成懸掛參考)... shared_ptr基於設計問題

 
struct Bar { }; 
struct Foo { Foo(Bar& bar) : bar(bar) { }; Bar& bar; }; 
int main() { 
    Bar bar; 
    Foo foo(bar); 
    // ... 
} 
... I need to do ...
 
struct Bar { }; 
struct Foo { Foo(shared_ptr bar) : bar(bar) { }; shared_ptr<Bar> bar; }; 
int main() { 
    shared_ptr<Bar> bar = make_shared<Bar>(); 
    Foo foo(bar); 
    // ... 
} 
... because I want to avoid of manual objects life-time tracking
Did I missed point in shared_ptr usage or this is pay for automatic life-time management ? Or maybe this is bad design sign ?

+0

'shared_ptr'應該謹慎使用。給定對象的生命週期是功能行爲的組成部分。如果你沒有明確的行爲規範,你就不會得到任何地方......如果你這樣做,那麼你不需要在任何地方使用'shared_ptr'。它不是靈丹妙藥,或者是子彈,有時候你會發現自己像瘋了一樣泄漏內存,因爲你有引用循環,不知道從哪裏開始,因爲你的協作圖很混亂:/ – 2011-03-22 14:53:39

+0

什麼是你的點?你想與shared_ptr一起工作,現在你是。由於main()是一個所有者,他應該有一個shared_ptr。使用shared_ptr比使用引用更加繁瑣。 – stefaanv 2011-03-22 14:56:28

+0

@Matthieu:在考慮所有者(shared_ptr)和用戶(weak_ptr)並使用分層方法時,shared_ptr可以真正幫助您。沒有設計,你只是用可能的內存泄漏來替換可能的懸掛指針 – stefaanv 2011-03-22 15:00:06

回答

2

It is a question of your object life cycle. You should use shared_ptr when you really share an object between multiple other objects.

In your case the owner of FOO and BAR must control the lifecycle of both. Maybe it is possible to make BAR a private member of you class FOO and let FOO control the life cycle.

I personally use the smart pointers to express the ownership of an object. Shared_ptr means that it is really shared and I am not the only owner of this object. Scoped or unique pointer show that I am the only owner of the object. If you want to transfer the ownership you can use auto_ptr or the C++0x move semantics.

I have seen at least in bigger projects that the lack of life cycle control will lead to dangling objects. So you don't have a direct memory leak any longer because of automatic life-time management but you get circular dependencies. Which lead to the same result.

To answer your question if this is bad design. It depends on what you are doing.

0

Have you tried working on values instead of pointers ?

+0

不,我不能這樣做,因爲pointee應該在幾個對象之間共享 – cybevnm 2011-03-22 15:05:07

2

It is a sign of bad design. shared_ptr存在於您的對象必須分配堆時。您不應該因爲可以使用shared_ptr而額外分配堆中的任何內容。堆棧仍然是英里的最佳選擇。

在開始決定如何實現它之前,您需要知道哪些對象需要在堆上運行,哪些需要在堆上運行,以及擁有權是什麼。然後你可以使用shared_ptr作爲實現工具。

+0

如果某個A類控制着B的生命期,而C由另一個需要指向B的控制,那該怎麼辦?我應該在這種情況下使用shared_ptr,或者再次,這是不好的設計? – cybevnm 2011-03-22 15:14:40

+0

@vnm:你可以強制'shared_ptr'作爲壞設計的補丁,但真正的解決方案需要*思考*。你需要考慮'A'是否負責'B'和'C',並且同時,如果'A'是否其他人應該持有對'B'的引用(似乎是'A'的內部細節) '可以在最後一個對象之前被破壞。在某些情況下,你會發現'B'不是由'A'擁有*,而是由'A'和'D'共享*,這是一個你想要將它轉換爲指針的提示(智能指針)。在其他情況下,它將由'A'擁有,'D'可能仍然有一個引用。 – 2011-03-22 15:45:31