Re: I am sorry for this...

From: Alf P. Steinbach (alfps_at_start.no)
Date: 02/01/05


Date: Tue, 01 Feb 2005 17:50:35 GMT


* Victor Bazarov:
>
> struct A { int i; A(int i) : i(i) {}; operator int() { return i; }};
> A const& f()
> {
> return 2;
> }
> int main()
> {
> int i = f();
> }
>
> is it legal or does the temporary get destroyed at the 'f's closing brace?

Answering my own original innocent question, now escalated into a full-blown
debate: it's the latter (as would also be the case with just using 'int').

§12.2/5 "A temporary bound to the returned value in a function return
statement (6.6.3) persists until the function exits".

If this was not the case, then gross inefficiencies would have to be
introduced to allocate memory for the result of a function for the
general case. With a reference result the referred object can be
any size whatsoever. Which means that the calling code cannot pre-
allocate space on the stack.

But of course we can wonder _why_ the standard requires near certain UB
(only if you don't use the result in any way can you avoid UB) instead
of simply disallowing this thing. Well, it may be the case that it one
return path the function returns a valid reference, while in another,
just a temporary to satisfy that warning-addicted compiler. Or it may
be the case that the programmer is engaging in Unholy Practices to obtain
the stack-pointer.

Although I would have preferred that the standard disallowed this...

Cheers,

- Alf

-- 
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?


Relevant Pages

  • C# code example - Point Class
    ... // List of cardinal directions useful in offset and coordinate ... public Point(int X, int Y) ... // If we have a valid reference ... public void Set ...
    (rec.games.roguelike.development)
  • Re: 2D array of structures
    ... programming habits. ... int str_len; ... // Declaring of menu items, necessary for later reuse in array ... // it's time to allocate memory on the fly, ...
    (comp.lang.c)
  • Problem in compiling a C code with MSVC++6.00
    ... When I save the file as a cpp file, it compiles and runs ... int p1; ... void checkfile; ... printf("cannot allocate memory for elements!"); ...
    (comp.lang.c)
  • Re: Basic Pointer Question...
    ... I coded a function to allocate memory and i am passing a pointer to the function. ... In addition, as malloc() is hidden within a function, freecan be easily forgotten. ...
    (comp.lang.c)
  • SetBkMode Transparent takes no effekt
    ... i'm developing a program to print out some richtext with pictures. ... public int FormatRange(bool measureOnly, PrintPageEventArgs e, int charFrom, ... Marshal.StructureToPtr(fr, lParam, false); ...
    (microsoft.public.win32.programmer.gdi)