2017-09-14 142 views
0

我写了这段代码并用gcc编译。 我希望得到结果“2”,但结果是“0”。通用引用和命名参数Ideom

其他编译器clang和vc打印“2”。 它是未定义的行为还是不行?

#include <stdio.h> 

struct Test { 
    Test& inc() { 
     ++value; 
     return *this; 
    } 

    int value = 1; 
}; 

int main() { 
    auto&& t = Test().inc(); // The life-time of the temporary might extended. 
    printf("%d\n", t.value); // gcc prints "0". dangling reference? 

    return 0; 
} 

c.f.建立reslut上http://rextester.com

+0

http://rextester.com/GBM44684 – sumomoneko

+0

我误解了自动演绎。 'auto && t = Test().inc()'不是'auto && t = Test(); t.inc();'。谢谢@Quentin! – sumomoneko

+0

'gcc-7 -sanitize-address-use-after-scope'可以检测到这个错误。 – sumomoneko

回答

2

转发引用(这就是普遍引用已被更名为)是不相关的 - 你会观察到有相同的行为定期参考。

的问题是,Test的寿命不延长,因为它不是直接结合至参考,如auto &&t = Test();会。相反,它的成员函数返回一个左值引用,该值用于推断并初始化tTest &(可以通过decltype(t)查看)。然后临时被破坏,引用现在悬而未决,并且使用它是未定义的行为。