c++ - Destructor called when objects are passed by value -


even though objects passed functions means of normal call-by-value parameter passing mechanism, which, in theory, protects , insulates calling argument, still possible side effect occur may affect, or damage, object used argument. example, if object used argument allocates memory , frees memory when destroyed, local copy inside function free same memory when destructor called. leave original object damaged , useless.

this written in c++: complete reference

in program here

#include<iostream>  using namespace std;  class sample {           public:          int *ptr;          sample(int i)          {          ptr = new int(i);          }          ~sample()          {          cout<<"destroyed";          delete ptr;          }          void printval()          {          cout << "the value " << *ptr;          }  };  void somefunc(sample x) {  cout << "say in somefunc " << endl; }  int main() {  sample s1= 10; somefunc(s1);  s1.printval(); } 

it generates runtime error object s1 destroyed when returns object. couldnt figure out why might happen, since copy should have been made. thought maybe because there no copy constructor present in class defination. surprised find if use function declaration

 void somefunc(sample &x) {  cout << "say in somefunc " << endl; } 

in declaration no error occurs. shouldnt error occur here because referenced? can explain happens in both cases.

this indeed because didn't provide copy constructor. compiler generate 1 you, trivial copy. , that's trivial copy of pointer that's problematic here.

for following declaration

void somefunc(sample x); 

there indeed copy when pass s1 function, copy have copy of pointer, is, 2 object point same int.

then, when exiting function, copy destroyed , delete pointer, leaving original object in calling code pointer deleted (remember, point same thing).

then, following declaration

void somefunc(sample &x); 

you don't have copy, problem doesn't show up. indeed, passing reference means inside function, sample object you're manipulating same 1 passed function, , won't destroyed when function exits.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -