Why I can access btn.Caption when btn is NIL?

谁说胖子不能爱 提交于 2020-01-14 07:11:29

问题


Why this code does not crash? T is nil. How it is possible to access Caption if T is nil?

procedure Crash;                                                                          
VAR T: TButton;
begin
 T:= NIL;
 T.Caption:= ''; <---------- this works
end;

回答1:


The TButton control is a wrapper around the Win32 Button control. It uses the Windows messaging system to operate upon it. And the core method for doing so, TControl.Perform(), has a built in safeguard against sending messages if Self is nil:

function TControl.Perform(Msg: Cardinal; WParam: WPARAM; LParam: LPARAM): LRESULT;
var
  Message: TMessage;
begin
  Message.Msg := Msg;
  Message.WParam := WParam;
  Message.LParam := LParam;
  Message.Result := 0;

  if Self <> nil then // <-- here
    WindowProc(Message); 

  Result := Message.Result;
end;

Caption is a property whose setter uses the non-virtual TControl.GetText() and TControl.SetText() methods, which can be safely called upon nil objects, as their functionality rely on sending various messages (WM_GETTEXTLEN and WM_SETTEXT) to the control, and only involve local variables or passed parameters. So the actual object is not accessed when nil, thus no crash.



来源:https://stackoverflow.com/questions/51161223/why-i-can-access-btn-caption-when-btn-is-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!