c++ - 使用三元表达式返回引用会导致运行时错误

标签 c++ c++11 visual-c++

由于某种原因,第二种方法不起作用。

concurrency::event<void( event_data& ), codec_cvt> &get_event( const string_type &event )
{
        auto it = events_.find( event );
        if ( it == events_.end( ) )
            throw /* exception */;
        return *it->second;
}

但是,此方法使用我喜欢的语法返回临时地址。什么时候应该准确,正确?

concurrency::event<void( event_data& ), codec_cvt> &get_event( const string_type &event )
{
    auto it = events_.find( event );
    return it != events_.end( ) ?
        *it->second :
        throw;
 }

最佳答案

在 C++14 之前,标准规定 false ? 形式的表达式的结果为 false ? throw 1 : xx 的拷贝,而不是 x 本身(从技术上讲,它应用了左值到右值、数组到指针和x 上的函数到指针转换以产生纯右值)。 N3337 [expr.cond]/2 :

If either the second or the third operand has type void, then the lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the second and third operands, and one of the following shall hold:

  • The second or the third operand (but not both) is a throw-expression ([except.throw]); the result is of the type of the other and is a prvalue.
  • [...]

这已由 Core issue 1560 更改:

A glvalue appearing as one operand of a conditional-expression in which the other operand is a throw-expression is converted to a prvalue, regardless of how the conditional-expression is used:

[...]

This seems to be gratuitous and surprising.

和段落 now reads :

If either the second or the third operand has type void, one of the following shall hold:

  • The second or the third operand (but not both) is a (possibly parenthesized) throw-expression ([expr.throw]); the result is of the type and value category of the other. The conditional-expression is a bit-field if that operand is a bit-field.
  • [...]

MSVC 还没有开始实现修复。 Clang 3.5+ 确实实现了它。

关于c++ - 使用三元表达式返回引用会导致运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40917184/

相关文章:

c++ - 有人可以解释为什么在释放指向它们的指针后我仍然有事件对象吗?

c++ - 将 lambda 传递给对象并从 lambda 内部修改该对象

c++ - 追加/打印/插入数组 c++ 函数问题

c++ - 在 C++ 迭代器问题中使用带有一对的映射作为键

c++ - 非类型参数包奇怪地展开

使用VC2010编译Python扩展

c++ - 本地类访问问题

c++ - 如何将下面的模板类泛化为调用任何函数?

使用运算符 = 时,c++11 unsigned char 变为 int

c++ - 套接字上的数据类型信息;动态初始化?