Domanda

Is it possible to have 2 different objects that share same reference counter?

Says I have

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

I want both objects alive until there is one reference to Foo or to Bar (so maybe no one is referencing Bar, but since Foo is referenced both will not be deleted).

È stato utile?

Soluzione 2

OK perfect I found the answer: http://www.codesynthesis.com/~boris/blog/2012/04/25/shared-ptr-aliasing-constructor/

The aliasing constructor! (code taken from the link)

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.
}

Altri suggerimenti

Put them in a struct and have the shared_ptr own that struct.

struct FooBar {
    Foo f;
    Bar b;
};
shared_ptr<FooBar> myFooBar;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top