0

是否可以有 2 个不同的对象共享相同的引用计数器?

说我有

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

我希望两个对象都活着,直到有一个对 Foo 或 Bar 的引用(所以也许没有人在引用 Bar,但由于 Foo 被引用,所以两者都不会被删除)。

4

2 回答 2

7

将它们放在一个结构中并拥有shared_ptr自己的那个结构。

struct FooBar {
    Foo f;
    Bar b;
};
shared_ptr<FooBar> myFooBar;
于 2013-07-08T15:45:20.713 回答
0

好的,完美我找到了答案: 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.
}
于 2013-07-08T19:28:41.887 回答