检查空指针
我正在构建一个 iPhone 应用程序并使用 C++,但在检查指针是否为空时遇到问题。
IMyInterface* myInterface;
if ( !myInterface ){ //doesn't work
myInterfacee->doSometing();
}
if ( myInterface != 0 ) { //doesn't work
myInterfacee->doSometing();
}
if ( myInterface != NULL ){ //doesn't work
myInterfacee->doSometing();
}
if ( myInterface != ( myInterface* )0 ) { //doesn't work
myInterfacee->doSometing();
}
如果 myInterface 设置或未设置,它仍然会进入每个语句并向我提供
程序收到的信号:“EXC_BAD_ACCESS”。
我该如何检查 myInterface 是否为空
I'm building a iphone app and using c++ and am having trouble checking if a pointer is null.
IMyInterface* myInterface;
if ( !myInterface ){ //doesn't work
myInterfacee->doSometing();
}
if ( myInterface != 0 ) { //doesn't work
myInterfacee->doSometing();
}
if ( myInterface != NULL ){ //doesn't work
myInterfacee->doSometing();
}
if ( myInterface != ( myInterface* )0 ) { //doesn't work
myInterfacee->doSometing();
}
If myInterface is or isn't set it still enters each statement and gives me
Program received signal: “EXC_BAD_ACCESS”.
How do i go about checking if myInterface is null
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的基本问题是您尚未初始化
myInterface
。假设
myInterfacee
只是一个拼写错误,那么以下内容都没有问题,并且它们都不会调用doSometing
:就我个人而言,我更喜欢前两个而不是第三个,并且不'根本不喜欢第四个,但这是风格问题而不是正确性问题。
我有点不相信这一点,但如果确实如此(您正在初始化
myInterface
,并且仍然看到if (!myInterface)
和if (myInterface != 0)
子句被执行),那么程序中的其他地方就存在严重错误。这些测试具有相反的含义,因此它们都显得真实的唯一方式是当发生未定义的事情时。Your basic problem here is that you haven't initialized
myInterface
.Assuming
myInterfacee
is just a typo, the following would all be fine, and none of them would calldoSometing
:Personally, I prefer the first two over the third, and don't like the fourth at all, but that's a question of style rather than correctness.
I sort of disbelieve this, but if that's really the case (you're initializing
myInterface
, and still seeing that both theif (!myInterface)
and theif (myInterface != 0)
clauses are executed), then there is something very wrong elsewhere in your program. Those tests have opposite meanings, so the only way they're both going to appear true is when something undefined is going on.您没有初始化
myInterface
,因此它的值是不确定的。您需要将其初始化为 null:或者,如果可以的话,通常最好在声明变量时将其初始化为有效状态:
您还应该考虑使用某种类型的智能指针,例如
shared_ptr
;智能指针使 C++ 中的内存管理变得更加简单。You do not initialize
myInterface
, so its value is indeterminate. You need to initialize it to null:Or, if you can, it is usually preferable to initialize the variable to a valid state when you declare it:
You should also consider using smart pointers of some kind, like
shared_ptr
; smart pointers make memory management in C++ far simpler.您的问题是默认情况下指针不会自动初始化为 NULL。您拥有的所有方法都应该可以工作,但是您需要在定义变量时将其初始化为 NULL。
Your problem is that pointers are not automatically initialized to NULL by default. All of the methods you have there should work, but you'll need to initialize your variable to be NULL when you define it.