【发布时间】:2019-08-29 06:43:34
【问题描述】:
下面这个简单的例子,为什么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
}
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
【问题讨论】:
-
此程序不产生任何输出并以代码 0 退出。带有
-O3优化标志的 main 内的所有语句都将被丢弃。 -
它给出了什么错误?
-
这其实是一个很有趣的问题。我会标记语言律师,并希望其中一位酋长接手这个。我既没有时间也没有专业知识。这一切都与生命周期扩展不具有传递性以及原始对象所在的位置有关。继续@StoryTeller。
-
@Bathsheba 你能快速解释一下为什么
b < a ? b : a这么有优势吗? -
@Michiel 问题是,如果绑定是直接的(例如,如果
min按值返回),ref2会将绑定临时的生命周期延长到自身的生命周期。因此,我猜是这个问题。
标签: c++ c++11 language-lawyer temporary-objects