It is guaranteed to work: logical AND and OR expression chains are evaluated from left to right, and if the first subexpression satisfies the condition, no further subexpressions are evaluated.
In your case, if currentNode
is null, it will never get dereferenced by the second subexpression, so the code is safe.
As @jdv pointed out though, this is called short-circuit evaluation, not lazy evaluation. The latter is a programming technique where you, transparently to the client, calculate a required value only the first time when it is concretely needed. A simplistic example:
class Example {
SomeClass *theObject = null;
public:
SomeClass *getTheObject() {
if (!theObject) {
theObject = doResourceConsumingCalculation();
}
return theObject;
}
};
Note that the client of Example
is unaware of the implementation detail that theObject
is evaluated lazily, so you are free to change back and forth between eager and lazy evaluation without affecting the public interface of the class.
(Of course, in real production code, getTheObject
should be implemented in a separate cpp file, and it should probably include synchronization, error handling code etc. This is just a simplistic example :-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…