Good practice in C ++ (lazy evaluation)

I have a question about lazy C ++ evaluation, can I be sure that this piece of code will always work, or is this a bad idea? if so why? thanks in advance

if (currentNode == 0 || * currentNode == element) {return; }

+7
c ++ lazy-evaluation
source share
3 answers

Work is guaranteed: the logical chains of the expressions AND and OR are evaluated from left to right, and if the first subexpression satisfies the condition, further subexpressions are not evaluated.

In your case, if currentNode is null, it will never be dereferenced by the second subexpression, so the code will be safe.

As @jdv pointed out, this is called a short circuit rating, not a lazy rating. The latter is a programming method when you, transparently to the client, calculate the required value only for the first time when it is specifically needed. The simplest example:

 class Example { SomeClass *theObject = null; public: SomeClass *getTheObject() { if (!theObject) { theObject = doResourceConsumingCalculation(); } return theObject; } }; 

Note that the Example client is not aware of the implementation details that theObject evaluates lazily, so you can freely switch back and forth between impatient 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 simplified example getTheObject

+19
source share

Yes, it is safe. It is called the short-circuited Boolean estimate.

For completeness, it is worth mentioning that, in principle, you can override || and && operators. If you do this, this will violate the short circuit rating and therefore will not be recommended.

+11
source share

For lazy evaluations in a multi-threaded environment, you should use boost :: once for a single load.

 class Example { mutable boost::once_flag flag; mutable SomeClass * theObject; void loadTheObject() const; public: Example() : flag(BOOST_ONCE_INIT), theObject( NULL ) { } SomeClass * getTheObject() const { boost::call_once( flag, boost::bind( &Example::loadTheObject, this ) ); return theObject; } }; 
+3
source share

All Articles