I've been skimming the most recent C++0x draft (N3126) and noticed the
function templates std::minmax. What I'm concerned about is that these
function templates -- since they return pair<const T&,const T&> --
interact quite badly with the auto type deduction feature. Since the
function returns basically two things, it is natural to store the
object and access its members later. One might be tempted to use the
new auto feature like this:
double f();
double g();
...
auto mm = minmax(f(),g());
At first sight, this seems harmless, but mm.first and mm.second are in
fact dangling references. With the other min and max functions that
only return 'const T&' this dangling reference problem is not as
severe because the references are not hidden behind a class and 'auto'
is never replaced by a reference type.
In my opinion, this should be fixed by using rvalue references and the
common_type trait so that if at least one argument is an rvalue, the
resulting pair also contains values instead of references:
template<class T, class U>
pair<
typename common_type<T,U>::type,
typename common_type<T,U>::type
>
minmax(T && t, U && u)
{
if (u<t) return {u,t}; else return {t,u};
}
This still allows the function template to return a pair of references
(when the arguments are reference-compatible lvalues) but it also
avoids the dangling reference problem in the example from above which
I guess will be a common trap when using std::minmax.
thanks for your attention,
Sebastian
--
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std...@netlab.cs.rpi.edu]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]