[英]Method in null class pointer (c++)
Let's say whe have 假设有
class Foo{
public:
bool error;
......
bool isValid(){return error==false;}
};
and somewhere 在某处
Foo *aFoo=NULL;
I usually would do if (aFoo!=NULL && aFoo->isValid()).....
我通常会这样做if (aFoo!=NULL && aFoo->isValid()).....
But what if in the isValid method I test the nullity: 但是,如果我在isValid方法中测试了无效性,该怎么办:
bool isValid(){return this!=NULL && error==false)
That would simplify the external testing with simply calling if (aFoo->isValid())
只需调用if (aFoo->isValid())
,即可简化外部测试
I've tested it in some compilers and it works but I wonder if it is standard and could cause problems when porting to other environments. 我已经在一些编译器中对其进行了测试,并且可以正常工作,但是我想知道它是否是标准的,并且在移植到其他环境时可能会引起问题。
The compiler is free to optimize away the check -- calling any non-static member of any class through an invalid (or NULL
pointer) is undefined behavior. 编译器可以自由地优化检查-通过无效(或NULL
指针)调用任何类的任何非静态成员都是未定义的行为。 Please don't do this. 请不要这样做。
Generally it would be bad design and in standard C++ it doesn't make much sense as your internal NULL check implies that you would call a null pointer, which is undefined behavior. 通常,这将是错误的设计,并且在标准C ++中,这没有多大意义,因为您的内部NULL检查意味着您将调用空指针,这是未定义的行为。
This topic was discusses here: Checking if this is null 这里讨论了这个主题: 检查是否为空
Why not simply a namespace-scope function like this? 为什么不这样简单地命名空间作用域呢?
bool isValid(Foo* f) {return f && f->isValid();}
An if
-Statement like if
语句像
if (aFoo->isValid())
Implies that the pointer is pointing to a valid object. 表示指针指向有效对象。 It would be a huge source of confusion and very error prone. 这将是一个巨大的混乱源,并且很容易出错。
Finally, your code would indeed invoke undefined behavior - aFoo->isValid
is per definition equivalent to (*aFoo).isValid
: 最后,您的代码确实会调用未定义的行为-每个定义aFoo->isValid
等效于(*aFoo).isValid
:
N3337, §5.2.5/2 N3337,第5.2.5 / 2条
The expression
E1->E2
is converted to the equivalent form(*(E1)).E2
; 表达式E1->E2
转换为等效形式(*(E1)).E2
;
which would dereference a null pointer to obtain a null reference, which is clearly undefined: 这将取消引用空指针以获得空引用,这显然是未定义的:
N3337, §8.3.2/5 N3337,§8.3.2/ 5
[ Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. [注意:尤其是,空引用不能存在于定义良好的程序中,因为创建此类引用的唯一方法是将其绑定到通过取消引用空指针而获得的“对象”,这会导致未定义的行为。 […] — end note ] […] —尾注]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.