c++ - Returning reference to temporary (built in types) -


from this thread clear string literal cannot used function returns const string& since there implicit conversion const char* std::string creates temporary.

but why warning "warning: returning reference temporary" if return type match , there no need conversion, e.g.:

include <iostream>  const int& test(){     return 2; }  int main(){      std::cout << test();  } 

no implicit conversion needed happen on return value of 2, why there warning? thought using test() pretty same doing

 const int& example = 2; 

which valid. additionally if change 2 2.2 (so double) program still runs (with same warning) despite fact there conversion double int? shouldn't running in issue similar how const char* returned string reference, if there conversion double int?

a temporary still created. §8.5.3/(5.2.2.2) applies1:

otherwise, temporary of type “ cv1 t1” created , copy-initialized (8.5) initializer expression. reference bound temporary.

this applies in second example. not apply prvalues of class type, or scalar xvalues: both

const a& = a(); // , const int& = std::move(myint); 

do not introduce temporary. however, isn't changing final result : in case, temporary bound reference destroyed @ end of return statement - §12.2/(5.2):

the lifetime of temporary bound returned value in function return statement (6.6.3) not extended; temporary destroyed @ end of full-expression in return statement.

that is, temporary destroyed before function exits, , program induces undefined behavior.


1 go on , quote entire list show why does, presumably waste of answer space.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -