huangshan wrote:
hi all
In what condition i need( or mast) a (templates)function return value by
reference?
can you give me a example
thanks
If you had provided a simple example - the exercise would have been far
more relevent for you.
Template or not, the exact same rules apply.
The "conditions" are
a) that the object/variable returned must be valid (not destroyed)
b) when is a reference, or a const reference, required?
Lets take an example and perhaps dispell what "returning" means:
void increment(int& r_n)
{
++r_n;
}
This function looks like its not returning anything, but it actually is
in the sense that its modifying a supplied parameter, not a *local*
copy of that parameter. So "returning" a reference is often safely
accomplished by having a reference as a parameter.
int& increment(int n) // bad code
{
return n;
}
That function is undefined behavious since integer n (a local copy)
ceases to exist when the function returns. Returning a reference to
garbage is garbage (TM).
Finally, and perhaps a tad more relevent, a *const* reference is the
safe way to return a private member of a class - safely. In this case,
obviously, n is valid but the goal here is not to allow somebody to
accidentally modify the private member via get() - just because they
have a reference to it.
template< typename T >
class N
{
T t;
public:
N() : t() { }
const T& get() const { return t; }
};
Its important to note that the const specifiers are very important
here. If you were to implement get() without the const specifiers,
you'ld be able to something nasty like get() = 6 and accidentally
modify member t through the reference - very,very bad side effect.
So its not just about "when returning a reference is valid" anymore but
rather "when does it make sense" to return what type of reference
(const or not?).