[odb-users] Re: Self persisting objects?

Boris Kolpackov boris at codesynthesis.com
Fri Aug 31 07:15:38 EDT 2012


Hi Oded,

Oded Arbel <oded at geek.co.il> writes:

> > So what most likely happens is you are using a smart pointer [...]
> 
> Not in this specific piece of code - its just a "this" pointer.

I mean your persistent class (Employee) uses a smart pointer as its
object pointer (normally specified with the 'pointer' pragma, the
--default-pointer ODB compiler option, or if you are using Boost
or Qt smart-pointer profiles). See Section 3.2, "Object and View
Pointers" for details.


> I changed it as you said and it looks to be working fine now. I'm not
> using sessions, but its something that I might want to look into in
> the future (possibly as an optimization), and I'm a bit confused
> regarding why is there a difference in the behavior of "this"
> dereferencing in regard to it being held by a smart pointer or not.

If your persistent class uses a smart pointer, say, shared_ptr, then
initializing it from a reference that was passed to persist() (which
is needed in order to enter this object into the session) is a bad
idea. Think what would happen if that reference is already managed
by another shared_ptr instance:

void 
my_persist (Employee& r)
{
  db.persist (r); // Initializing another shared_ptr from &r
                  // is bad news.
}

shared_ptr<Employee> p (new Employee (...));
my_persist (*p);

That's why if you are using smart pointers, persist() will enter
the object into the session only if you pass the smart pointer:

db.persist (p);

If you need to convert 'this' to a shared_ptr, look into the 
shared_from_this mechanism.

Boris



More information about the odb-users mailing list