在给定表达式返回对类型的引用时出错:`cond?*this:throw()`

Adr*_*ian 6 c++ g++ visual-c++ clang++ c++14

这似乎是一个错误,但我只是想确认一下.以下是否良好形成?如果没有,为什么不呢?

#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;
}
Run Code Online (Sandbox Code Playgroud)

VC++2015 R3默认解决方案开关下,我得到:

warning C4172: returning address of local variable or temporary
Run Code Online (Sandbox Code Playgroud)

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");
                                      ^
Run Code Online (Sandbox Code Playgroud)

但是,clang version 3.9.1 (tags/RELEASE_391/final)用开关-Wall -pedantic没有问题.

使用return *this;当然没有问题.

T.C*_*.C. 10

由于你有一个C++ 14标签,代码是100%格式良好的C++ 14.

核心问题1560在这里删除了无偿的左值到右值转换,并且作为缺陷报告解决方案,它最终应该一直应用于提供这种模式的C++ 98/03模式的编译器.

另见GCC错误64372.