void __fastcall TFChild::FormShow(TObject *Sender)
{
bt = new TButton(this);
bt->Parent = this;
bt->Name = "bt1" ;
bt->OnClick = BControl;
}
//---------------------------------------------------------------------------
생성할때 아래와 같이 Owner를 인자로 주느냐 마느냐에 따라 다른데요
new TButton(NULL); ==> 이경우는 delete해줘야 하구요
new TButton(this); ==> 이경우는 delete안해줘도 됩니다.
왜 두번째 처럼 Owner를 넘겨주면 delete를 안해줘도 되느냐면요?
bt는 생성되면서 자신의 주인(Owner)를 this 즉 TFChild 인스턴스로 설정해 줬습니다.
VCL의 TComponent * 를 상속받은 class는 자신이 죽을때( delete 또는 free) 될때
자신의 자식들을 delete하고 죽습니다.
위와같은경우 TFChild 폼이 free되면서 동적으로 생성한 bt를 delete하게 됩니다.
아래는 VCL의 TComponent 소멸자 코드입니다.
destructor TComponent.Destroy;
begin
Destroying;
if FFreeNotifies <> nil then
begin
while Assigned(FFreeNotifies) and (FFreeNotifies.Count > 0) do
TComponent(FFreeNotifies[FFreeNotifies.Count - 1]).Notification(Self, opRemove);
FreeAndNil(FFreeNotifies);
end;
DestroyComponents;
if FOwner <> nil then FOwner.RemoveComponent(Self);
inherited Destroy;
end;
참고로
Owner와 Parent 에관하여 좀 헷갈려 하시는 분이 많아서....
아래 글들을 읽어보세요
http://cbuilder.borlandforum.com/impboard/impboard.dll?action=read&db=bcb_faq&no=15
http://cbuilder.borlandforum.com/impboard/impboard.dll?action=read&db=bcb_tutorial&no=38
그럼..
반짝반짝 님이 쓰신 글 :
: MDI 테스트 중인데요
:
: 버튼을 동적으로 만들었는데
:
: 폼 클로우즈 할때 버튼 delete를 따로 해줘야 하는건가용?
:
: 아님 자동으로 해제 되는건가요?
:
:
:
:
:
: void __fastcall TFChild::FormClose(TObject *Sender, TCloseAction &Action)
: {
: Action = caFree;
: }
: //---------------------------------------------------------------------
: void __fastcall TFChild::FormShow(TObject *Sender)
: {
: bt = new TButton(this);
: bt->Parent = this;
: bt->Name = "bt1" ;
: bt->OnClick = BControl;
: }
: //---------------------------------------------------------------------------
: void __fastcall TFChild::BControl(TObject *Sender)
: {
:
:
: }
: void __fastcall TFChild::Button1Click(TObject *Sender)
: {
: delete bt ;
: bt = NULL ;
: }