good practice in c++ (lazy evaluation)

佐手、 提交于 2019-12-18 04:53:26

问题


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

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