qt 判断指针对象是否释放
答案:2 悬赏:50 手机版
解决时间 2021-02-24 12:48
- 提问者网友:ミ烙印ゝ
- 2021-02-23 22:21
qt 判断指针对象是否释放
最佳答案
- 五星知识达人网友:雪起风沙痕
- 2021-02-23 23:25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TA = class
private
Fs: string;
public
constructor Create(s: string);
destructor Destroy;override;
procedure test;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
A: TA;
begin
A := TA.Create('test');
A.Free;
//A := nil;
//if A <> nil then
if Assigned(A) then
A.test;
end;
{ TA }
constructor TA.Create(s: string);
begin
Fs:= s;
end;
destructor TA.Destroy;
begin
Fs:= '';
inherited;
end;
procedure TA.test;
begin
ShowMessage(Fs);
end;
end.
例如以上代码,A对象所指向的堆内存已经free了,但无论判断A是否为nil或者用assigned判断,都可以调用A.test而不出错。应该怎么判断A已经Free而不至于执行A.test呢?
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TA = class
private
Fs: string;
public
constructor Create(s: string);
destructor Destroy;override;
procedure test;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
A: TA;
begin
A := TA.Create('test');
A.Free;
//A := nil;
//if A <> nil then
if Assigned(A) then
A.test;
end;
{ TA }
constructor TA.Create(s: string);
begin
Fs:= s;
end;
destructor TA.Destroy;
begin
Fs:= '';
inherited;
end;
procedure TA.test;
begin
ShowMessage(Fs);
end;
end.
例如以上代码,A对象所指向的堆内存已经free了,但无论判断A是否为nil或者用assigned判断,都可以调用A.test而不出错。应该怎么判断A已经Free而不至于执行A.test呢?
全部回答
- 1楼网友:摆渡翁
- 2021-02-24 01:01
c++之父的c++圣经《c++程序设计语言 特别版》中说:
大家不要听某些人说用(p==null)或(p!=null)的格式,c++之父认为这样写是不好的,提倡直接写(p)或(!p)的形式。
在win32开发中,if ( null == p )是极好的写法。
但不要写成:
if ( p == null )
c++之父主要是反对使用“null”,因为在某些特殊的开发环境叫,“null”并非补定义成地址0,也可能是一个跟平台相关的,用于标记非法地址的其它地址。
但按照c++标准的规定,只有等于0的地址可以被随便delete多次,因此如果是别的地址,那至少c++标准就给不了任何说法。
至于是if(p == 0)和if(p !=
不过,从代码的可扩展性上讲,写成后者可能好一些,因为如果有一天你决定改用一些原生指针的包装类(比如类似那种auto_ptr模板的)来代替直接操作原生指针,而那个类可能重载了operator!,后者可能让你直接利用这些设施
林锐提倡if ( p == null
)是从代码的可读性上考虑的,一看就是在判断一个指针,而不是判断一个bool值,它提倡只有bool值才使用if(p)或者if(!p)的形式。
bs是从可移植方面考虑。
if( p == null
另外,不要写成if( p == null )这样的形式,应该写成:if ( null== p )。
如果你误写成了if ( null = p
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯