c++ - Why destructor is calling after function scope ending when object reference passed as parameter? -


why destructor being called after function (pass(sample const &ob1)) scope ends, when object reference passed parameter? why creating new object in function pass(), while passing object reference?

help me on this, i'm getting memory dump error

#include<iostream> using namespace std;   class sample { public:     int *ptr;     sample()         {         cout<<"this default constructor & addr  "<<this<<endl;     }     sample(int i)     {         cout<<"this single parameter constructor & addr "<<this<<endl;         ptr=new int[i];      }     void disp()      {         cout<<"hello \n";     }     ~sample()     {         cout<<"destructor & addr "<<this;         delete ptr;     }  };    sample pass(sample const& ob1) {  for(int i=0;i<5;i++)     ob1.ptr[i]=10; return ob1;  }  int main() {    sample obj(5); sample copy; cout<<"before calling \n"; obj.disp(); pass(obj); copy.disp(); cout<<"after calling \n"; return 0; } 

that's because return value:

sample pass(sample const& ob1) {    //...    return ob1;   } 

and it's not guaranteed rvo occur. in case, i'm not sure can occur.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -