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


I think, to use std::unique_ptr and std::move instead of Gtk::manage is a good 
idea, but it is more difficult to use:

  auto widget = std::make_unique<Button>("some button");
  notebook.append_page(std::move(widget), "something");
OK, but widget does no longer point to the botton, compare with the example at
  notebook.child_property_tab_expand(*widget) = true;
Should lead to a segmentation fault.

#include <iostream>
#include <memory>
int main() { 
  auto p = std::make_unique<int>(4);
  cout << *p << endl;
  auto p2 = std::move(p);
  cout << *p2 << endl;
  cout << *p << endl;
  return 0;
segmentation fault (core dumped)  ./a.out

So, in order to create a widget, move it into a container and use it 
afterwards, we have to create two pointers (the unique-pointer and a normal 

  auto widget = std::make_unique<Button>("some button");
  Gtk::Widget* widget_to_expand = *widget;
Wrong, right is:
Gtk::Widget* widget_to_expand = widget.get();
  notebook.append_page(std::move(widget), "something";

Another idea is to change the add-methods to return a pointer to the object 
added. So the code can be written as (for clearity with Gtk::Button* instead 
of auto):
Gtk::Button* button = container.add_unique(std::make_unique<Gtk::Button>("a 

For this, Container::add_unique() must be a (simple?) template, so it returns 
the exact type for the pointer (Gtk::Button*) and not Gtk::Widget*:
template<class X>
X* Container::add_unique(std::unique_ptr(X) widget)
  X* p = widget.get();
  return p;
virtual void Container::add(std::unique_ptr<Gtk::Widget> widget);

It would be difficult to change our API to make it unnecessary to ever refer
to a child Widget* after we've added it to a container.

That is not what I have with Gtk::manage at the moment. I use it so I can say: 
Gtk, make the memory management for me. But I still need to change objects 
after adding them to a container (set the sensitivity / the state of a toggle 


Attachment: signature.asc
Description: This is a digitally signed message part.

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