Question

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;
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top