2

Is this undefined behavior? If not, what is the behavior?

// In some external library with, say, header "a.h" void f(int &&x) { x = 5; // Which memory does this assignment apply to? } #include "a.h" int main() { f(7); // At this point, where is the value of 5? return 0; } 
15
  • 1
    No, and 5 is still 5. Commented Apr 16, 2014 at 0:34
  • But where did the assignment x = 5 go to? Commented Apr 16, 2014 at 0:35
  • 2
    Inside f, a temporary of is created with value 7, exactly as if we wrote f(const int& x), only this is not const. x refers to this temporary, and since it's not const, we can change it. However, this is only a local variable so outside f(), this value is lost. Commented Apr 16, 2014 at 0:40
  • 5
    I knew I just saw this somewhere. codepuppy.co.uk/cpptuts/Beginning/references.php Commented Apr 16, 2014 at 0:40
  • 2
    @Dimitrios If you pass a variable, f(int&&) simply won't match - you would need f(int), f(int&), or f(const int&). Commented Apr 16, 2014 at 0:52

1 Answer 1

4

C++11 8.5.3 describes initialization of references (including rvalue references).

It says:

Otherwise, a temporary of type “cv1 T1” is created and initialized from the initializer expression using the rules for a non-reference copy-initialization (8.5). The reference is then bound to the temporary.

So, a temporary of type int is bound to the rvalue reference, and thrown away immediately after the call returns.

Section 12.2 (Temporaries) gives examples very similar to yours.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.