1

Why is the destructor being called after function (pass(sample const &ob1)) scope ends, when object reference is passed as parameter? Why is it creating a new object in function pass(), while we are passing an 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 is default constructor & addr  "<<this<<endl;
    }
    sample(int i)
    {
        cout<<"this is 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;
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
sai
  • 155
  • 2
  • 2
  • 10

3 Answers3

2

That's because you return by value:

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

And it's not guaranteed that RVO will occur. In this case, I'm not even sure it can occur.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • what we have to do that it should not calling the destructor in that function? – sai Jun 05 '12 at 11:47
  • @sai I see that you're not using the return type. So just don't return anything. If you need to return by value, you can't prevent it. – Luchian Grigore Jun 05 '12 at 11:50
0

You are returning a sample by value; this involves construction and destruction of a sample (although in certain circumstances it can be optimised away).

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • even though im not returning any value ( i tried return type void), same memory dump error coming... – sai Jun 05 '12 at 12:16
  • @sai: Ok, but that's a separate issue. You should read about the [Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). – Oliver Charlesworth Jun 05 '12 at 12:17
  • thanks yar,now i know rule of three and im cleared with copy constructor,copy assignment operator – sai Jun 06 '12 at 11:56
0

Function pass() is creating a new object because the object is being returned by value ,not by reference . Returning object by value will invoke a copy constructor and a new object will be created (temporary object) which will be destroyed as soon as the function returns.

To avoid creation of a temporary object,try returning object by reference. Also the default constructor is not initializing the integer pointer causing memory dump error .

sample const& pass(sample const &ob1)
{

for(int i=0;i<5;i++)
ob1.ptr[i]=10;
cout << "pass & addr " << &ob1 << endl ;

return ob1;

}
sample()    
{
    cout<<"this is default constructor & addr  "<<this<<endl;
    this->ptr = new (int);
}