개체의 가상 메서드 내에서 개체를 간접적으로 삭제할 수 있습니까? "정의 된 동작"(객체를 삭제 한 후에 아무 것도 액세스하지 않는 한)입니까?
예 :직접 가상 메서드에서 개체를 간접적으로 삭제합니다. 정의 된 행동입니까?
#include <memory>
#include <stdio.h>
using std::tr1::shared_ptr;
struct Child{
virtual void selfdestruct() = 0;
virtual ~Child(){
fprintf(stderr, "child destroyed\n");
}
};
typedef shared_ptr<Child> ChildPtr;
struct Parent{
ChildPtr child;
void clear(){
fprintf(stderr, "clear\n");
child = ChildPtr();
}
Parent();
};
struct DerivedChild: public Child{
Parent* parent;
virtual void selfdestruct(){
fprintf(stderr, "selfdestruct\n");
if (parent)
parent->clear();
}
DerivedChild(Parent* p)
:parent(p){
}
};
Parent::Parent(){
child = ChildPtr(new DerivedChild(this));
}
int main(int argc, char** argv){
Parent p;
p.child->selfdestruct();
fprintf(stderr, "child is 0x%08x\n", p.child);
return 0;
}
출력 :
selfdestruct
clear
child destroyed
child is 0x00000000
이 정의 행동하지 않으면, 내가 대신 무엇을 할 수 있습니까?
"자식 개체에는 가상 소멸자가 필요합니다." 그것은 "오타"였습니다. 나는 그것을 가상으로 만들겠다고 맹세 할 수있었습니다. 그러나 개체가 스스로를 파괴해야하는 모든 유형의 상황은 설계의 최선이 아닙니다. " 제 경우에는 객체가 그것을 지우는 것을 유발할 수있는 상황이 있습니다. 그래서 내가 그 질문을했다. – SigTerm
@SigTerm :'delete this'는 붉은 깃발이지만, 간접적으로 복잡한 절차가 끝나면 자신을 처분하는 것은 그리 좋지 않습니다. – Potatoswatter