Re: std::max(short,long) doesn't work
On Oct 19, 12:34 pm, Phil Endecott
<spam_from_usenet_0...@chezphil.org> wrote:
Howard Hinnant wrote:
Yes you can, just explicitly provide template arguments:
std::max<long>(s,l);
Ah, that's interesting. So if I provide an explicit type then it
behaves like my non-template function f above.
If you use it this be forewarned that you should not catch the return
value as a const reference (const long&), but catch it as a long
instead. If you catch it as a reference:
const long& m = std::max<long>(s,l);
then you risk having a reference to a destructed temporary (the
temporary long created from converting from s).
And g++ doesn't seem to give a warning in this case, which is a bit
disconcerting as it normally does give some sort of message if you do
something bad with a temporary.
How can it? You're initializing a reference with a reference.
At that point, it has no way of knowing anything about the
lifetime of the object the reference refers to. And in the call
to max, everything seems fine as well, since the lifetime of the
temporary is longer than that of the reference argument. To
catch the error and warn, it would have to trace the lifetimes
and values through the function.
Try turning up optimization. Maybe it warns then.
(Optimization will cause additional flow analysis, particularly
over the inlined functions, which are otherwise treated as
separate functions.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34