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

僤鯓⒐⒋嵵緔 提交于 2019-12-23 15:41:33

问题


#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?)


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/13280437/is-it-legal-to-take-the-address-of-a-const-lvalue-reference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!