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:

  1. is safe return value(2); ?

    does created object expire once functions ends ? if how receive it?

  2. why need declare const if making reference variable on example?

  1. 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.

  1. 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

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -