[odb-users] Weak pointer can't be converted to shared pointer

Boris Kolpackov boris at codesynthesis.com
Fri Apr 20 06:32:36 EDT 2012


Hi Wayne,

weak_ptr will only be valid if there is at least one shared_ptr still
pointing to the object (for more information on the shared/weak pointers
semantics, refer to their documentation).

In case of ODB, this would normally mean that for weak_ptr to be valid,
there needs to be another object with shared_ptr pointing to the same
object or there needs to be a session.

As an example, consider these two classes:

class employee
{
  shared_ptr<employer> employer_;
};

class employer
{
  weak_ptr<employer> ceo_;
};

If you do something like this:

shared_ptr<employer> er (db->load<employer> (...));

Then the er->ceo_ pointer will be loaded, assigned to weak_ptr, and,
since there is no other shared_ptr pointing to it, immediately freed.
And the er->ceo_ will be NULL.

On the other hand, if we have something like this:

session s;
shared_ptr<employer> er (db->load<employer> (...));

Then the er->ceo_ pointer will be loaded, cached in session (as shared_ptr),
and assigned to weak_ptr. Since the session holds shared_ptr, er->ceo_ will
be valid.

Similarly, if we have something like this:

shared_ptr<employee> ee (db->load<employee> (...));

Provided that ee is the CEO, then ee->employer_.ceo_ will be valid since
we hold shared_ptr.

Boris



More information about the odb-users mailing list