2013-07-08 95 views
0

有可能有2個不同的對象共享相同的引用計數器嗎?C++ 11共享Ptr,共享相同的引用計數器

說我必須

shared_ptr<Foo> myFoo; 
shared_ptr<Bar> myBar; 

我想,直到有一個參考美孚或酒吧兩個對象活着(所以也許沒有人引用酒吧,但由於富被引用既不會被刪除)。

+0

可替換地,我需要知道如何重新解釋鑄造的shared_ptr 到shared_ptr GameDeveloper

+4

氣味等的[XY問題](http://meta.stackexchange.com/questions/66377 /是什麼 - 是最XY-問題)。你爲什麼需要這個? –

+0

這是一個C++ protip:如果你認爲你需要投射,但不知道如何,你不需要投射。 –

回答

7

將它們放在一個結構中,並讓shared_ptr擁有該結構。

struct FooBar { 
    Foo f; 
    Bar b; 
}; 
shared_ptr<FooBar> myFooBar; 
+4

並從中你可以使用shared_ptr [ctor 8從外層空間](http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr)獲得shared_ptrs到個別部分,如果真的有必要的話。 –

+0

@ R.MartinhoFernandes「ctor 8 from outer space」Brilliant! –