c++ - Lifecyle of a returned class constructor call -
here code:
class value{ public: int x; value(int y):x(y){ } }; value getval(){ return value(2); } int main() { const value & rec = getval(); return 0; } my questions:
is safe
return value(2);?does created object expire once functions ends ? if how receive it?
why need declare
constif making reference variable on example?
- is safe return
value(2);
if receive return value below it's allowed (hence safe):
value rec = getval(); // `const value rec = getval();` or
const value& rec = getval(); with both above cases, scope of variable not destroyed , remains until scope of receiver i.e. rec.
refer return value optimization.
- why need declare const if making reference variable?
receiving simple reference not allowed.
suggested in 1. can declare simple variable. compiler not make unwanted copy. if want make rec unmodifiable, may declare const reference.
Comments
Post a Comment