当对象引用作为参数传递时,为什么在函数 (pass(sample const &ob1)) 范围结束后调用析构函数?为什么它在函数 pass() 中创建一个新对象,而我们正在传递一个对象引用?
帮帮我,我收到内存转储错误
#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;
}