On 9/26/14, 1:38 PM, Wouter van Ooijen wrote:
>
> Even for such a question (which is IMO much better than asking for nitty
> gritty details) I would be more interested in range of solutions such a
> person would propose, and his arguments for and against each solution.
>
> Today I had to compose (multiple-choice) questions for the C++ exam for
> my course. I visted a number of sites that show such questions. To my
> surprise I could use only a very limited number (maybe 5%), because the
> rest was about wording, syntax details, or just plain wrong.
>
> Note that some detail questions *are* good questions. Like: what is
> probably wrong with this function?
>
> T & f();
>
> (answer: what does that returned reference refer to? A global -> yuk! A
> local -> worse! An allocated heap object -> who is responsible for
> managing this object?)
>
> Wouter van Ooijen
>
The first thing I would say is probably wrong with the code is that "f"
is too short of a name for a function, unless, maybe, it is being used
in the prototype of a function declaring a function pointer to be passed in.
Second, while maybe it is odd enough to raise a review question, I don't
think that "probably" wrong is right.
Some very correct applications of this sort of function (I presume this
is intended to be a global function that returns a reference):
1) f() is a maker function and is returning the created object. When the
user is done they are expected to remove the object either with a member
function or another free function, think of it sort of like new, but
returning a reference rather than a pointer.
2) f() is returning a singleton like object. f() will check if the
singleton is already created, and if not create it and return a
reference to it. Presumably some link has been made somewhere to
properly dispose of the object at program end, or perhaps it is
reference counted and there is another function to indicate that we are
done, and if no one needs it still, it can be disposed of.
3) f() could also return a "global" object, whose exact type might not
be known at the time of the compiling of the caller, but it is known to
be a subtype of some base "T". This allows the caller to get access to
the object, and the final type might not be known to link time, when an
appropriate module is linked in, defining the object and the access
function. With dynamic linking, it might even be at run time.
Returning an "auto" local to f() is bad, as such an object is gone by
the time you get to the caller.