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
}
实时示例 - 生成:
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;
}
实时示例 生成的结果如下:
<source>:14:38: error: '<anonymous>' is not a constant expression
constexpr int const& ref2 = min(x,y+1);
^
Compiler returned: 1
b < a ? b : a
很有优势? - lubgrmin
返回值),ref2
将会将绑定的临时变量的生命周期延长到它自己的生命周期。所以我猜这就是问题的关键。 - Angew is no longer proud of SO