这似乎是一个错误,但我只是想确认一下。下面的格式是否正确?如果不是,为什么不呢?
#include <iostream>
struct X
{
int value;
constexpr X(int value) : value(value) {}
constexpr X& do_something(int x)
{
return x < 3 ? *this : throw("FAIL");
//return *this;
}
};
int main()
{
X x(2);
std::cout << x.do_something(1).value << std::endl;
}
在使用默认解决方案开关的 VC++2015 R3
下,我得到:
warning C4172: returning address of local variable or temporary
g++ (GCC) 5.4.0
带有开关 -Wall -pedantic
我得到:
error: invalid initialization of non-const reference of type ‘X&’ from an rvalue of type ‘X’
return x < 3 ? *this : throw("FAIL");
^
但是,带有开关 -Wall -pedantic
的 clang 版本 3.9.1 (tags/RELEASE_391/final)
没有问题。
使用 return *this;
当然没有问题。
最佳答案
因为你有一个 C++14 标签,所以代码是 100% 格式良好的 C++14。
Core issue 1560在这里删除了无偿的左值到右值转换,作为缺陷报告的解决方案,它最终应该一直应用到提供这种模式的编译器的 C++98/03 模式。
另见 GCC bug 64372 .
关于c++ - 给定表达式 : `cond ? *this : throw()` 返回对类型的引用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43054494/