简体   繁体   中英

Is it legal to take the address of a const lvalue reference?

#include <iostream>
int foo()
{
  return 0;
}

int main()
{
  const int& a = foo();
  std::cout << &a << std::endl;
}

In this code, a binds to a rvalue. Is it legal to take its address? (And by legal I mean: in the code ill-formed? Am I causing an undefined behaviour?)

This is fine. In C++11 you can even do this:

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

You can kind of think about temporaries like this (conceptually and in general):

x = func(); // translated as:

auto __temporary = func();
x = __temporary;
__destruct_value_now_and_not_later(__temporary);

Except if x is the definition of a reference type, the compiler notes that you're purposefully referring to the temporary value and extends its lifetime by removing the early destruction code, making it a normal variable.

Yes. Until the variable a goes out of scope, the temporary it captures is valid. Herb Sutter can explain it better .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM