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

标签 c++ visual-c++ g++ c++14 clang++

这似乎是一个错误,但我只是想确认一下。下面的格式是否正确?如果不是,为什么不呢?

#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 -pedanticclang 版本 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/

相关文章:

C++:带 D2XX 驱动程序的 Bit-banging(USB 到串行 UART)FTDI 模块

visual-c++ - 在 Visual C++ 2008 中安装 Boost 库

c++ - 带有 clang 的模板阴影错误

c++ - 无法将 dbus 与 C++ 链接

c++ - 雅可比矩阵的 5 DOF 逆运动学

c++ - QLabel 的输入/输出?

c++ - 是否可以使用 C++ 中的 [] 运算符访问复数的实部和虚部

c - 有没有办法在 Windows 7 上以编程方式激活 Windows

GCC代码统计/分析

c++ - 在 C++ 中使用哪个库来解析命令行参数