使用C ++短路行为在使用前预先检查指针? [英] Using C++ short circuit behavior to pre-check a pointer before use?

查看:52
本文介绍了使用C ++短路行为在使用前预先检查指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎有用,有危险吗?



if(指针&& *指针==值)

{

...

}



谢谢



:Ron

This seems to work, is it dangerous?

if(pointer && *pointer == value)
{
...
}

Thanks

:Ron

推荐答案

这是一种很好的做法,但还不够。

问题是你没有(标准)方法来测试该指针变量是否包含有效的指针或垃圾。语言标准没有规定变量需要在创建时清除。如果 int * p 默认情况下 null ,则由编译器和运行时实现决定。据我所知,没有常用的编译器在声明时将代码添加到零变量,因为它需要时间。编写程序员的工作不是C / C ++的思维方式。全局变量在大多数时间都归零,但字段和本地变量不归零。

因此,为了确保不会遇到麻烦,请确保尽快初始化指针(重新接受声明) - 在同一个声明中,如果可能的话。
It is good practice, but not enough.
The problem is that you have no (standard) means to test if that pointer variable contains valid pointer or garbage. The language standard doesn't specify that the variables need to be cleared on creation or not. It is up to the compiler and runtime implementation if int* p will be null by default or not. As I know there is no commonly used compiler that adds the code to zero the variable when declared, because it takes time. And doing the coder's job is not the C/C++ way of thinking. Global variables are zeroed most of the time, but fields and local ones not.
So, to be sure not to run into trouble, make sure to initialize pointers as soon as possible (relatieve to the declaration) - in the same statement, if possible.


你知道,编程是一件非常危险的事情。不,这不是更危险。 :-)



请参阅: http:// en。 wikipedia.org/wiki/Short-circuit_evaluation [ ^ ]。



您应该注意的主要事项是运算符优先级。请参阅: http://en.cppreference.com/w/cpp/language/operator_precedence [< a href =http://en.cppreference.com/w/cpp/language/operator_precedencetarget =_ blanktitle =New Window> ^ ]。



正如你所看到的,'&&'在比较运算符后位于第13位,所以一切都很好。如有疑问,可以使用'()'。 :-)



-SA
You know, programming is a pretty dangerous thing. No, it's not more dangerous. :-)

Please see: http://en.wikipedia.org/wiki/Short-circuit_evaluation[^].

The major thing you should be careful with would be operator precedence. Please see: http://en.cppreference.com/w/cpp/language/operator_precedence[^].

As you can see, '&&' goes at position 13, after comparison operator, so everything's fine. When in doubt, you can use '()'. :-)

—SA


这篇关于使用C ++短路行为在使用前预先检查指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆