Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

good practice in c++ (lazy evaluation)

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; }

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...