Re: temporaries and const&
* dragoncoder:
On Apr 30, 2:21 pm, "Alf P. Steinbach" <a...@start.no> wrote:
* dragoncoder:
Thanks for the response. In the same context, does this code invoke
undefined behaviour ?
#include <iostream>
template <class T1, class T2>
const T1& max ( const T1& a, const T2& b )
{
return ( a > b ) ? a : b;
}
int main() {
int i = 20; double d = 40;
std::cout << max ( i, d ) << std::endl;
return 0;
}
Yep. It would be less clear-cut if both arguments were "int const&".
I'd have to read the standard's fine print about the ?:-operator to
figure that out, but I think that when the types are identical reference
types it can produce a reference result, thus no UB in that case.
I am a bit confused now. Are you saying it is a case of UB because the
temporary is being accessed after the function call ?
Yes.
The temporary no longer exists at the point where it's used.
Or, in practice it may still exist, but in practice it may also have
been overwritten.
That being the
case a simple function like below will also invoke UB ? Am I right ?
Yes.
const int& bar ( ) { return 10; }
std::cout << bar() << std::endl;
Please enlighten me.
<url:
http://www.amazon.com/Computer-Parables-Enlightenment-Information-Age/dp/0931137136>.
Hm, I'd better buy that book, and quite a few others!
Can't go on recommending books I've never even read (I only have two C++
books, namely TCPPPL in 1st and 2nd edition, the 3rd edition on
permanent load to someone I don't know, and Modern C++ Design, yet I go
on recommending Accelerated C++, C++ Primer, You Can Do It!, etc.).
Thanks again.
You're welcome.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?