On Monday, December 24, 2012 19:05:32 monarch_dodra wrote:
> On Monday, 24 December 2012 at 17:37:54 UTC, Andrei Alexandrescu
> wrote:
> > An important smoking gun is C++'s min(), which is allows
> > writing unsafe code without casts.
> > 
> > const int& haveANiceDay = min(4, 5);
> > 
> > 
> > Andrei
> 
> But that example  actually works correctly.

Um. How?

It's created a reference to a temporary, and that temporary will no longer 
exist once the statement has completed. So, haveANiceDay ensd up pointing to 
garbage. Sure, there's a decent chance that it'll give you the value of 4 
initially, but there's no guarantee whatsoever that it will or that it will 
continue to do so, as the program is free to reuse that memory for something 
else. The only thing that _might_ save you is the fact that the temporary is 
likely higher up on the stack and therefore less likely to have its memory 
reused as long as haveANiceDay exists lower on the stack. I don't believe that 
there's any guarantee of that however. Once the statement has completed, 
haveANiceDay could point to anything.

- Jonathan M Davis

Reply via email to