delete가 어떻게 작동하는지 알고 싶습니다. 주 기능에서 cfact
object
을 삭제했습니다. 하지만 여전히 cfact->Hello()
은 오류를 발생시키는 대신 작동합니다. 삭제하는 동안 발견 한 디버그 동안 cfact
메모리를 해제합니다. 최대한 factory* c2fact = newfun.Newfun("c2_fact");
라인 실행 cfact
일부 메모리 위치를 가져옵니다.C++에서 delete 키워드 opearation과 혼동을 느낍니다.
어떻게? 개념을 이해하는 데 나를 도우십시오.
class factory{
public:
virtual void Hello() = 0;
};
class c_fact: public factory
{
public:
void Hello(){
cout << "class c_fact: public factory"<<endl;
}
};
class c2_fact: public factory
{
public:
void Hello(){
cout << "class c2_fact: public factory"<<endl;
}
};
class callFun{
public:
virtual factory* Newfun(string data)
{
if(data == "c_fact")
{return new c_fact;}
else
{return new c2_fact;}
}
};
class newFun:public callFun{
public:
factory* Newfun(string data)
{
if(data == "c_fact")
{return new c_fact;}
else if (data == "c2_fact")
{return new c2_fact;}
}
};
int main()
{
newFun newfun;
factory* cfact = newfun.Newfun("c_fact");
delete cfact; //Deleted the instance
factory* c2fact = newfun.Newfun("c2_fact");
cfact->Hello();//Still it prints the output
c2fact->Hello();
system("pause");
return 0;
}
예상되는 결과는 무엇입니까? 삭제 된 객체에서 함수를 호출하고 있습니다. 이것은 정의되지 않은 동작이며 출력 인쇄를 포함하여 모든 일이 발생할 수 있습니다. –
@PeterWood : 'cfact-> Hello();'가 실패하기를 원합니다. 우연히 나는이 행동을 보았다. 그래서, 나는 물어볼 생각을 이해할 수 없었다. –
가상 소멸자를 사용해야합니다. – Jeka