由于某种原因,第二种方法不起作用。
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 : x
是 x
的拷贝,而不是 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/