有可能有2個不同的對象共享相同的引用計數器嗎?C++ 11共享Ptr,共享相同的引用計數器
說我必須
shared_ptr<Foo> myFoo;
shared_ptr<Bar> myBar;
我想,直到有一個參考美孚或酒吧兩個對象活着(所以也許沒有人引用酒吧,但由於富被引用既不會被刪除)。
有可能有2個不同的對象共享相同的引用計數器嗎?C++ 11共享Ptr,共享相同的引用計數器
說我必須
shared_ptr<Foo> myFoo;
shared_ptr<Bar> myBar;
我想,直到有一個參考美孚或酒吧兩個對象活着(所以也許沒有人引用酒吧,但由於富被引用既不會被刪除)。
OK完美,但我找到了答案: http://www.codesynthesis.com/~boris/blog/2012/04/25/shared-ptr-aliasing-constructor/
頻迭構造! (從鏈接取代碼)
struct data {...};
struct object
{
data data_;
};
void f()
{
shared_ptr<object> o (new object); // use_count == 1
shared_ptr<data> d (o, &o->data_); // use_count == 2
o.reset(); // use_count == 1
// When d goes out of scope, object is deleted.
}
將它們放在一個結構中,並讓shared_ptr
擁有該結構。
struct FooBar {
Foo f;
Bar b;
};
shared_ptr<FooBar> myFooBar;
並從中你可以使用shared_ptr [ctor 8從外層空間](http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr)獲得shared_ptrs到個別部分,如果真的有必要的話。 –
@ R.MartinhoFernandes「ctor 8 from outer space」Brilliant! –
可替換地,我需要知道如何重新解釋鑄造的shared_ptr到shared_ptr –
GameDeveloper
氣味等的[XY問題](http://meta.stackexchange.com/questions/66377 /是什麼 - 是最XY-問題)。你爲什麼需要這個? –
這是一個C++ protip:如果你認爲你需要投射,但不知道如何,你不需要投射。 –