Re: Replace Gtk::manage() with std::unique_ptr<>?



On Mon, 2016-02-08 at 10:18 +1300, Ian Martin wrote:
Correct me if I'm wrong, but doesn't Gtk::manage work more like a
shared 
pointer? i.e. maintain a count of the references to the object,
deleting 
the object pointed to when the ref count goes to zero.

Not quite. GObject has simple reference-counting. But widgets have
actual ownership by container widgets, with some reference-counting
thrown in to confuse things. But in the end, containers can choose when
to destroy their child widgets.

Calling Gtk::manage() means "let the container destroy this", or more
fundamentally, it means "I am giving away the ownership".

As you've said, using unique_pointer mandates a design with only one 
access point to the controlled object,

I don't think that's quite true. You can get (a pointer to) the widget
back from its container widget.

 and there's plenty of interesting 
things you may want to do to widgets after construction.

You'd call std::move() when giving the ownership to the container
widget, not right after construction.

I like the explicit handing over of ownership of std::move()ing a
std::unique_ptr<> and I like that I'm encouraged to do that when I've
finished with the setup of the object.

  We use 
Gtk::manage() freely because it keeps track of widget memory use for
us, 
but doesn't control access to it within the code.

The intent is similar with std::unique_ptr<> and std::move(), but it's
a general and standardized technique.

One option might be to provide 2 variants for Gtk::manage(); one
using 
shared_pointer semantics and one using unique_pointer, with a default
to 
shared (because it'd be backwards compatible).
It's also considered wise to receive a std::unique_ptr as a
parameter
if the method really plans to take ownership. For instance:
   void Foo::take_thing(std::shared_ptr<Thing> thing);
I think you've typed std::shared_ptr<Thing> when you meant 
std::unique_ptr<Thing> ?

Yes, sorry.

-- 
Murray Cumming
murrayc murrayc com
www.murrayc.com





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