[gtkmm] Returning objects from member functions and operators

At Murray's suggestion, I'd like to bring up a topic that I think would be useful to address in gtkmm/glibmm 2.4, which is how objects are returned from functions and operators.

There are a number of places in glibmm/gtkmm where objects are returned on the stack from functions. These are invariably returned as non-const objects. This results in behavior which is inconsistent with the behaviors of C++ built-in types. Scott Meyers presents a detailed discussion of this in Effective C++ item 21:


For example in glib/glibmm/main.h there is a get_default() function defined for MainContext:

   static Glib::RefPtr<MainContext> get_default();

This function returns a non-const object. So it is possible to do something like this:

   return MainContext::get_default() = 0;

This clearly is not correct code, but it is something that could easily happen by accident. If one were to do something similar with integers, the compiler would flag it, because the built-in operators return const values. However, since the function is returning a non-const object on the stack, the assignment is legal. Wrong, but legal.

Basically, so long as there is an appropriate copy constructor for the class being returned, there's no reason why any function or operator should ever return a non-const object on the stack. Doing so increases the risk of incorrect code, whereas making sure to return objects on the stack as const carries no penalty.

I suggest that going forward, all functions and operators in glibmm/gtkmm that return an object on the stack should return that object as const, e.g.:

   static const Glib::RefPtr<MainContext> get_default()

Doing so should not impact existing programs in any way, unless they contain incorrect code.


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