Is it legal to accept a link address const lvalue?

#include <iostream> int foo() { return 0; } int main() { const int& a = foo(); std::cout << &a << std::endl; } 

In this code, a bound to an rvalue. Is it legal to accept his address? (And by law, I mean: is it badly formed in the code? Am I causing undefined behavior?)

+4
source share
2 answers

This is normal. In C ++ 11, you can do this:

 int&& a = foo(); a = 123; 

You can somehow think of such temporary (conceptually and generally):

 x = func(); // translated as: auto __temporary = func(); x = __temporary; __destruct_value_now_and_not_later(__temporary); 

Except that x is a definition of a reference type, the compiler notes that you purposefully refer to a temporary value and extend its lifetime by removing the early destruction code, making it normal.

+5
source

Yes. As long as the variable a does not go beyond the scope, the temporary capture is valid. Herb Sutter can explain this better .

+2
source

Source: https://habr.com/ru/post/1444697/


All Articles