소멸자가 개체 참조가 매개 변수로 전달 될 때 함수 (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;
}
'패스'가 사본을 반환하고 있다는 것을 알고 계십니까? – Fanael
''delete ptr;''이 잘못되었으므로, 어떤 값을 반환하지 않더라도 (new 타입을 사용했기 때문에)''new []'' – Davidbrcz