CoffeDeveloper
CoffeDeveloper

Reputation: 8325

C++11 Shared Ptr, share the same reference counter

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

Upvotes: 0

Views: 184

Answers (2)

CoffeDeveloper
CoffeDeveloper

Reputation: 8325

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

Upvotes: 0

Puppy
Puppy

Reputation: 147036

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

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

Upvotes: 7

Related Questions