问题
I have some question about lazy evaluation of c++, can I be sure that this snippet of the code will always work, or it is bad idea? if Yes, why? Thanks in advance
if(currentNode == 0 || *currentNode == element){ return; }
回答1:
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 :-)
回答2:
Yes this is safe. It is called short-circuit boolean evaluation.
For completenes it deserves mention that in principle it is possible to override the || and && operators. If you do so, this will break the short circuit evaluation, and is therefore not reccomended.
回答3:
For lazy-evaluation in a multi-threaded environment you should consider using boost::once to perform the one-time loading.
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;
}
};
来源:https://stackoverflow.com/questions/4613551/good-practice-in-c-lazy-evaluation