[gtkmm] 2 Glib::RefPrt<>s from one instance.



Greetings (again):

  This isn't so much a bug as an undocumented design quirk.

  Given a decendent memory model, Glib::RefPtr<>s work fine:

    foo *orig = new foo; Glib::RefPrt<foo> a(orig); b = a; c = b;

    "orig" won't be deleted until a, b and c are all out of scope.
    This is a good thing.

  If, however, you construct 2 RefPtr<>s from the same instance then that
instance's destructor gets called twice.

    foo *orig = new foo;
    Glib::RefPrt<foo> a(orig); Glib::RefPrt<foo> b(orig);

    If "a" exits scope before "b", then b->whatever() is pointing to
    free memory.  This bit me on the tush last night.

  The reason is because "orig" is required to set it's reference
counter to 1 on instantiation, and the constructor doesn't increment
it.  I assume that this is because Glib::RefPrt<>s tend to get wrapped
around things like PixBufs, which start with a reference of 1.

  At a minimum I'd recommend documenting this behavior.  I'd like to
believe that I'm not the only one that tripped up on this.

  I'd also recommend adding an additional Glib::RefPrt<> constructor
which allows the caller to decide whether to do the initial incrememnt.
This would make Glib::RefPrt<> a bit more general.

  Maybe something like Glib::RefPrt<foo> a(new foo, true) would
increment the counter.   Glib::RefPrt<foo> a(new foo, false) would
work like Glib::RefPrt<foo> a(new foo).

  Lastly, the most general solution is to implement Glib::RefPrt<foo>
in terms of a more general class, say Glib::GenRefPrt<foo>.
The GenRefPrt<foo> constructor would default to incrementing the
reference counter, but would have an optional paramater to prevent it, for
those times you use them on PixBufs and the such.

  Sorry to be so long winded, but I'm working on a project that needs a
smart pointer, and I'd rather not reinvent the wheel.

					Dale

Attachment: pgpvzLbLSSKOp.pgp
Description: PGP signature



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]