在下面的简单示例中,为什么不能将ref2绑定(bind)到min(x,y+1)的结果?

#include <cstdio>
template< typename T > const T& min(const T& a, const T& b){ return a < b ? a : b ; }

int main(){
      int x = 10, y = 2;
      const int& ref = min(x,y); //OK
      const int& ref2 = min(x,y+1); //NOT OK, WHY?
      return ref2; // Compiles to return 0
}

live example-产生:
main:
  xor eax, eax
  ret

编辑:
我认为,下面的示例更好地描述了一种情况。
#include <stdio.h>


template< typename T >
constexpr T const& min( T const& a, T const& b ) { return a < b ? a : b ; }



constexpr int x = 10;
constexpr int y = 2;

constexpr int const& ref = min(x,y);  // OK

constexpr int const& ref2 = min(x,y+1); // Compiler Error

int main()
{
      return 0;
}

live example产生:
<source>:14:38: error: '<anonymous>' is not a constant expression

 constexpr int const& ref2 = min(x,y+1);

                                      ^

Compiler returned: 1

最佳答案

这是设计使然。简而言之,只有直接绑定(bind)了临时名称的命名引用才能延长其生命周期。



您没有直接绑定(bind)到ref2,甚至还通过return语句传递了它。该标准明确表示不会延长使用生命周期。在某种程度上使某些优化成为可能。但是最终,因为很难理解当引用传入和传出函数时应该扩展哪个临时对象。

由于编译器可能会在您的程序没有任何未定义行为的假设下进行积极的优化,因此您可能会看到这种情况。未定义在其生存期之外访问值的操作,这是return ref2;所做的,并且由于未定义行为,因此简单地返回零便是有效的行为。编译器不会破坏任何契约(Contract)。

关于c++ - 为什么const引用不能延长通过函数传递的临时对象的生命周期?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55567962/

10-13 06:51