user2485710 user2485710 - 1 year ago 70
C++ Question

C++11/14 and return( ... ) vs return

In C++ you are allowed to write a return statement that looks like :

return ( ... );

which is different from the more popular :

return ... ;

In particular the first version returns the address/reference of something that is local to the stack of the function which contains that

Now why something would like to return a reference to something that, at that point, has no lifetime ?

What are the use case for this idiom ? Considering the new buzzword and features from C++11 and C++14 there is a different usage for this ?

Answer Source

Pre C++1y the parenthesized version of the return is identical, if we look at the C++11 draft standard section 6.6 Jump statements, the grammar for return is:

return expressionopt ;

return braced-init-list ;

an expression can be any expression and we can see from section 5.1 Primary expressions says (emphasis mine going forward):

A parenthesized expression is a primary expression whose type and value are identical to those of the enclosed expression. The presence of parentheses does not affect whether the expression is an lvalue. The parenthesized expression can be used in exactly the same contexts as those where the enclosed expression can be used, and with the same meaning, except as otherwise indicated.

In C++1y we can use delctype(auto) to deduce return types and this changes the situation as we can see from the draft C++1y standard section auto specifier says:

When a variable declared using a placeholder type is initialized, or a return statement occurs in a function declared with a return type that contains a placeholder type, the deduced return type or variable type is determined from the type of its initializer.[...]

and contains the following examples:

auto x3a = i; // decltype(x3a) is int

decltype(auto) x3d = i; // decltype(x3d) is int

auto x4a = (i); // decltype(x4a) is int

decltype(auto) x4d = (i); // decltype(x4d) is int&

and we can see there is a difference when using delctype(auto) and parenthesized expressions. The rule that is being applied is from section Simple type specifiers paragraph 4 which says:

For an expression e, the type denoted by decltype(e) is defined as follows:

and includes the following bullets:

— if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;


— otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download