worksofcraft
September 27th, 2010, 10:43 PM
I have a class that I derive lots of other classes from and an important part of it is a virtual operator that converts it to a constant char *.
Lately I'm using it to wrap some Gtk widgets and one of them is the combobox from which said operator retrieves the currently active text like so:
operator cs_combo::charptr() const {
gchar *Text = gtk_combo_box_get_active_text(Widget);
return (charptr) Text;
}
Seems easy enough except the text string retrieved from gtk must be freed by a call to g_free(Text) :shock: and as we all know, C/C++ do not have automatic garbage collection.
So my first impulse was to make Text a member of my cs_combo structure and simply dispose of it when a a new call for active text is made, and also in the destructor of course.
However, then I will be modifying the cs_combo structure and so the operator will not be on a read only structure and hence not an override for the virtual method of the base class.
I can think of three options:
remove "const" from the base class and all other classes that derive from it.
get rid of the old charptr operator and make one that returns a C++ string or even a glib ustring.
Create an independent list of items to submit to g_free effectively making a primitive sort of garbage collector.
I think option 2 would be easiest to work with, but I am concerned about the overhead it will produce: unnecessarily allocating and copying strings in countless places.
I wonder if any other C++ programmers have views or alternative solutions: How would you do it?
Lately I'm using it to wrap some Gtk widgets and one of them is the combobox from which said operator retrieves the currently active text like so:
operator cs_combo::charptr() const {
gchar *Text = gtk_combo_box_get_active_text(Widget);
return (charptr) Text;
}
Seems easy enough except the text string retrieved from gtk must be freed by a call to g_free(Text) :shock: and as we all know, C/C++ do not have automatic garbage collection.
So my first impulse was to make Text a member of my cs_combo structure and simply dispose of it when a a new call for active text is made, and also in the destructor of course.
However, then I will be modifying the cs_combo structure and so the operator will not be on a read only structure and hence not an override for the virtual method of the base class.
I can think of three options:
remove "const" from the base class and all other classes that derive from it.
get rid of the old charptr operator and make one that returns a C++ string or even a glib ustring.
Create an independent list of items to submit to g_free effectively making a primitive sort of garbage collector.
I think option 2 would be easiest to work with, but I am concerned about the overhead it will produce: unnecessarily allocating and copying strings in countless places.
I wonder if any other C++ programmers have views or alternative solutions: How would you do it?