yamiez yamiez - 8 days ago 8
C++ Question

Returning reference using a ternery expression causes runtime error

For some reason, the second method will not work.

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;
}


However, this method using my preffered syntax is returning an address of a temporary. When it should be exactly, correct?

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;
}

Answer

Standard writes in 8.5.4.1: List-initialization

Note: List-initialization can be used

  • as the initializer in a variable definition (8.5)
  • as the initializer in a new expression (5.3.4)
  • in a return statement (6.6.3)
  • as a function argument (5.2.2)
  • as a subscript (5.2.1)
  • as an argument to a constructor invocation (8.5, 5.2.3)
  • as an initializer for a non-static data member (9.2)
  • in a mem-initializer (12.6.2)
  • on the right-hand side of an assignment (5.17)

The more minimalistic return 1?{}:{}; is invalid too, what you want is impossible.