Re: The use of RefPtr



Eddie Carle wrote:
On Sat, 2009-03-07 at 02:14 -0500, Hubert Figuiere wrote:
Why do you think there is a Glib::RefPtr<TreeModel> ? It is not just
for the show. It will unref when the Glib::RefPtr<> is destroyed,
therefor when you leave the scope.

I understand what RefPtr does. It is just like any other
referenced/shared pointer out there like boost::shared_ptr except that
the reference is stored in the actual object it is pointing to.

I still don't understand WHY you want to make it more complicated. The
allocation policy using Glib::RefPtr<> is actually the much simplier
part of Gtkmm.

I don't know how else to explain. See, shared pointers are great. I like
them. A drawback however is that you cannot point them to something
sitting on the stack. Therefore the use of a shared pointer in theory
forces you to dynamically allocate the memory in the free store instead
of the stack. I want my TreeModel on the stack, I don't want it in the
free store. I know it's size at compile time, and it's lifetime will be
directly related to it's scope, so I want it on the stack. I'm in a
crunch for resources and must avoid new/delete as much as possible.

Since we've established that in theory I can't use stack data with a
true shared pointer, the question is: can I trick it? Can I prevent the
dreaded "delete" from ever happening? My idea is that if I manually call
reference() on the TreeModel, the reference count will always be one
higher than the amount of RefPtrs pointing to the TreeModel and they
will never try to deallocate it and crash the program (since it is in
the stack and the shared pointer will try to deallocate it as though it
is in the free store). So again, my question is: will this trickery
cause some sort of behind the scene glitch or memory leak? Since the
TreeModel is designed for dynamic allocation/deallocation, can it safely
be destroyed in the traditional stack "scope runs out" way?

No, this won't really gain you anything, because the Gtk::TreeModel (C++) wrapper is only a thin layer around the GtkTreeModel (C) object. The C object is *always* allocated on the heap even if the C++ wrapper is allocated on the stack. So the only thing you'll save by attempting to allocate the C++ type on the stack is the size of a single pointer that got moved from the heap to the stack.

--
jonner


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