what can't non-const object receive temporary object

a function returns a temporary object like

1
2
3
4
int myfun(){
int x = 0;
return x;
}
this function will return a temporary integer now

void fun1(const int & num); this function can receive from myfun()

BUT

void fun2(int & num); this function cannot receive from myfun()

Why is that, Moreover what is lifetime of a temporary object like one returned in myfun() ???
Only one way to say you never know the reference in C/C++.
I'm not sure of the exact technical details as to why it is possible / impossible, but logically it makes sense. If you pass a const reference, it means you are pointing to read-only memory. However, non-const means that you could potentially overwrite the rvalue from myfun. It would serve no purpose, and could potentially create odd bugs if you overwrote temporary memory.

The lifetime of an rvalue such as from myfun is typically until the end of the statement (generally demarcated by the semicolon). Hence, the variable's lifetime is still in effect until the call to the function it is being passed to is finished.

On a side note, if you specifically wanted a function accepting an rvalue reference, from C++11 you can do the following:
void fun3(int&& num);
Last edited on
C++ has a special case for allowing a const reference to bind to the value of a temporary.
NT3 wrote:
If you pass a const reference, it means you are pointing to read-only memory.
Nope, we just had a thread on this:
http://www.cplusplus.com/forum/lounge/141633/#msg748603 (see also the next page)
@LB
I meant logically, not technically. I musn't have worded it right.
what is lifetime of a temporary object like one returned in myfun()

I believe a temporary lasts until the last reference to it goes out of scope. Thus in your example, fun1(fun()); would cause the return value of fun() to last until fun1 returns.

Note that it lasts until the last references goes away, not the last pointer. The key here is that the compiler can tell when a reference goes away.

I may be wrong on the details, but basically if the compiler can tell that it's needed, the compiler will keep it around.
To answer the "why" part, as far as I have heard, the reasoning early in the C++ history was as follows: If the function is declared to take a non-const reference, it's saying that it's taking an out- or in/out-parameter. But a temporary passed into a function call in some expression cannot be accessed by the calling code again in another part of the expression, so if the function is treating it as an out-parameter, the function's expectations are wrong: the output is going nowhere. So it was made an error, detectable at compile time.
Later as C++ became used more, the need to modify temporaries in order to take over the resources they manage became known (look at C++98's auto_ptr_ref for one solution), and eventually C++11 introduced support for that via rvalue references.

Last edited on
Topic archived. No new replies allowed.