c ++中的良好实践(懒惰评估) [英] good practice in c++ (lazy evaluation)

查看:78
本文介绍了c ++中的良好实践(懒惰评估)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些关于懒惰评估c ++的问题,我可以确定这段代码总是工作,还是坏主意?如果是,为什么?提前感谢

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

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


推荐答案

确保工作:逻辑AND和OR表达式链

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.

在你的情况下,如果 currentNode 为null,它永远不会被第二个子表达式取消引用,因此代码是安全的。

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

正如@jdv指出的,这被称为 short - 电路评估,而不是延迟评估。后者是一种编程技术,其中,对客户端透明地,仅在具体需要的第一时间计算所需的值。一个简单的例子:

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

请注意,示例的客户端实现细节的实现细节, 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.

(当然,在实际生产代码中, getTheObject 应该在一个单独的cpp文件中实现,它应该包括同步,错误处理代码等。这只是一个简单的例子: - )

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

这篇关于c ++中的良好实践(懒惰评估)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆