具有空捕获列表的Lambda仍然能够从全局范围捕获对象? [英] Lambda with empty capture list still able to capture objects from global scope?

查看:85
本文介绍了具有空捕获列表的Lambda仍然能够从全局范围捕获对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个全局静态对象。没关系,这些都是Qt类,与问题无关。

I have a couple global static objects. Never mind that these are Qt classes, that's irrelevant to the matter.

static const QStringList JpegFileExtensions = QString::fromLatin1(jpegExtensions).split(" ");
static const QStringList TiffFileExtensions = QString::fromLatin1(tiffExtensions).split(" ");
static const QStringList RawFileExtensions = QString::fromLatin1(rawExtensions).split(" ");
static const QStringList PngFileExtensions = QString::fromLatin1(pngExtensions).split(" ");

现在,我有另一个静态对象,该对象由某个函数初始化,该函数采用先前的对象并计算结果:

Now, I have another static object that's initialized by some function that takes the previous objects and computes the result:

inline QString GetAllSupportedExtensions() {
   QStringList extensions = QStringList() << JpegFileExtensions << TiffFileExtensions << RawFileExtensions << PngFileExtensions;
   for (QString& item: extensions)
        item.remove("*.");

   return extensions;
}

static const QString AllSupportedExtensions = GetAllSupportedExtensions();

但是由于此 GetAllSupportedExtensions 函数未使用在其他任何地方,我都想摆脱它,以免使名称空间混乱。自然,我想到使用lambda,它是一个匿名函数:

But since this GetAllSupportedExtensions function is not used anywhere else, I wanted to get rid of it so that it doesn't clutter the namespace. Naturally, I thought of using a lambda, it being an anonymous function:

static const QStringList AllSupportedExtensions = []() -> QStringList {
    QStringList list = QStringList() << JpegFileExtensions << TiffFileExtensions << RawFileExtensions << PngFileExtensions;
    for (QString& item: list)
        item.remove("*.");

    return list;
} ();

请注意空捕获列表和空参数列表。它可以在Windows(msvc-2013)和OS X(clang-700.1.81)上编译并运行。为何如此?

Note the empty capture list and empty list of arguments. It compiles and works on Windows (msvc-2013) and OS X (clang-700.1.81). How so? Is it standard-compliant, should it even compile with an empty capture list?

推荐答案

lambda不会捕获任何内容吗?它是否符合标准?您正在函数中使用全局变量。 Lambda的函数主体是放置在表示Lambda的未命名类的 operator()内的内容。您可以使用任何功能执行此操作。

The lambda is not capturing anything. You are using global variables in a function. The function body of a lambda is what is put inside operator() of an unnamed class that represents the lambda. You can do this with any function.

您可以通过简单的示例看到此功能

You can see this working with this simple example

int i = 10;

class Foo
{
public:
    void operator()() { i = 20; }
};

int main(){

    Foo f;
    f();
    std::cout << i;
}

在线示例

这篇关于具有空捕获列表的Lambda仍然能够从全局范围捕获对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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