它对于一个lambda是有效的,本质上,关闭它自己吗? [英] Is it valid for a lambda to, essentially, close over itself?

查看:103
本文介绍了它对于一个lambda是有效的,本质上,关闭它自己吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个lambda递归是否有效?

Is this lambda recursion valid?

#include <functional>
#include <iostream>

int main() {
   std::function<int(int)> g = [&g](int k) {
       return (k ? k * g(k-1) : 1);
   };

   std::cout << g(10); // 3628800
}

似乎编译并运行确定,但我很紧张关闭 g 在我初始化它的语句。严格有效性为1-10 ...?

It appears to compile and run ok, but I'm nervous about closing over g in the same statement that I initialise it. Strict validity on a scale of 1-10...?

推荐答案

在捕获 g 通过引用已声明,因此名称可供使用:

At the point at which you capture g by reference, it has been declared, so the name is available for use:


/ 1一个名字的声明点紧接在其完整的声明器(第8条)之后和它的初始化器之前

3.3.2/1 The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer

在初始化之前以有限的方式使用对象 - 基本上,不依赖于值的任何东西都可以:

You are allowed to use objects in limited ways before they are initialised - basically, anything that doesn't depend on the value is OK:


3.8 / 6 before对象的生命周期已经开始,但在对象将占据的存储之后
已经被分配[...]可以使用引用原始对象的任何glvalue,但只能在有限的
方法中使用。 [...]使用不依赖于其值的glvalue的属性是明确定义的。

3.8/6 before the lifetime of an object has started but after the storage which the object will occupy has been allocated [...] any glvalue that refers to the original object may be used but only in limited ways. [...] using the properties of the glvalue that do not depend on its value is well-defined.

,你正在做的是定义明确的。

So by my understanding, what you are doing is well-defined.

(虽然,超级的,我不认为它是指定的自动对象的存储分配,8.3 .2 / 5说引用应该被初始化为引用一个有效的对象,而不定义有效,所以有范围可以认为它没有被很好地定义)。

(Although, being ultrapedantic, I don't think it's specified when the storage for an automatic object is allocated, and 8.3.2/5 says that "a reference shall be initialized to refer to a valid object" without defining "valid", so there's scope to argue that it's not well-defined).

这篇关于它对于一个lambda是有效的,本质上,关闭它自己吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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