Is compound if checking for null and then other condition in C++ always safe? [duplicate]

社会主义新天地 提交于 2019-12-11 12:15:40

问题


(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).

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?
{ /* ... */ }

It relies on ptr != NULL being checked before 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?


回答1:


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++ 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.

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
}



回答2:


It is safe as long as operator && is not overloaded

C++ standard draft says (N3337 - 5.14 Logical AND operator):

The && operator groups left-to-right. The operands are both contextually converted to type bool (Clause 4). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.



来源:https://stackoverflow.com/questions/21776927/is-compound-if-checking-for-null-and-then-other-condition-in-c-always-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!