Reputation: 33605
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();
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;
} ();
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?
Upvotes: 0
Views: 1298
Reputation: 180980
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;
}
Upvotes: 6