NOTE: Last year, I posted three new GotWs numbered #103-105. I decided leaving a gap in the numbers wasn’t best after all, so I am renumbering them to #89-91 to continue the sequence. Here is the updated version of what was GotW #104.
What should factory functions return, and why?
While spelunking through the code of a new project you recently joined, you find the following factory function declaration:
widget* load_widget( widget::id desired );
1. What’s wrong with this return type?
2. Assuming that widget is a polymorphic type, what is the recommended return type? Explain your answer, including any tradeoffs.
3. You’d like to actually change the return type to match the recommendation in #2, but at first you worry about breaking source compatibility with existing calling code; recompiling existing callers is fine, but having to go change them all is not. Then you have an “aha!” moment, realizing that this is a fairly new project and all of your calling code is written using modern C++ idioms, and you go ahead and change the return type without fear, knowing it will require few or no code changes to callers. What makes you so confident?
4. If widget is not a polymorphic type, what is the recommended return type? Explain.