小编Khu*_*dov的帖子

为什么const引用不能延长通过函数传递的临时对象的寿命?

在下面的简单示例中,为什么不能ref2绑定到结果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
}
Run Code Online (Sandbox Code Playgroud)

现场示例 -产生:

main:
  xor eax, eax
  ret
Run Code Online (Sandbox Code Playgroud)

编辑: 我认为以下示例更好地描述了一种情况。

#include <stdio.h>


template< typename T >
constexpr T const& min( T …
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer temporary-objects c++11

45
推荐指数
3
解决办法
2683
查看次数

标签 统计

c++ ×1

c++11 ×1

language-lawyer ×1

temporary-objects ×1