如果检查null是否复合,然后C ++中的其他条件总是安全的? [英] Is compound if checking for null and then other condition in C++ always safe?
问题描述
(这个问题是复合如果检查为空,然后C中的其他条件总是安全吗?但是关于 C ++ ,而不是C.有人指出问题应该更具体。)
(this question is an exact copy of Is compound if checking for null and then other condition in C always safe? but about C++, not C. It was pointed out that the question should be more specific).
我一直在使用以下类型的 if
条件很长时间。
I have been using the following type of if
condition for a lot of time.
char* ptr = ...;
if (ptr != NULL && ptr[0] != '\0') // <=== is this always safe?
{ /* ... */ }
它依赖于 ptr!= NULL
在 ptr [0]之前检查!='\ 0'
。
在所有标准,编译器和架构下是否安全?或者是否有可能在 ptr!= NULL
ptr [0]!='\ 0' >?
Is it safe under all standards, compilers, architectures? Or is there a possibility that ptr[0] != '\0'
will be checked before ptr != NULL
?
推荐答案
在这种情况下是安全的。 短路评估表示&&的RHS ;
只有在第一个为真时才会评估运算符。
It is safe in this case. Short-circuit evaluation means that the RHS of the &&
operator will only be evaluated if the first is true.
C ++允许覆盖 bool运算符&&
用于用户定义的类型。使用覆盖&&&
不会进行短路评估,因此安全性会丢失。重载此运算符并不是一个好主意。
C++ allows to override bool operator &&
for user defined types. Using an overriden &&
does not follow short-circuit evaluation, so the safety is lost. It is rarely a good idea to overload this operator.
这是一个显示超载&& $ c $行为的示例c>运算符:
Here's an example showing the behaviour of an overloaded &&
operator:
struct Foo {};
bool operator && (const Foo&, const Foo&) { return true; }
#include <iostream>
Foo make_foo()
{
std::cout << "making foo\n";
return Foo();
}
int main()
{
make_foo() && make_foo(); // evaluates both expressions
}
这篇关于如果检查null是否复合,然后C ++中的其他条件总是安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!