1
#define WIRED\
  []() {\
    return new MyClass; \
  }()

MyClass* a = WIRED;

I don't understand the first []() and the last () in the MACRO. Can any expert explain this? Thanks.

Shoe
  • 74,840
  • 36
  • 166
  • 272

2 Answers2

4

It's a lambda returning a dynamically allocate MyClass that is created and executed in place.

Specifically:

[](){...}

is the lambda; and the remaining () is the invocation of the lambda.


It's a useless lambda AFAIK and you can simply write:

MyClass* a = new MyClass;

or better:

std::unique_ptr<MyClass> ptr(new MyClass);
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • Of course, macros are ugly, and this could be done just as well with an inline function. It may be useless as-is, but I'd guess it was introduced to enable centralised changes to the code. Maybe it's in an `#ifdef` block which the OP didn't show - perhaps a different definition of `WIRED` is supplied when a specific macro (e.g. `DEBUG_ALLOCATIONS`) is defined. – Angew is no longer proud of SO Jul 02 '14 at 06:44
2

You may need to understand lambda function from C++11.

I believe you can understand this:

MyClass* CreateMyClass() { return new MyClass; }
...

std::function<MyClass* ()> creator_function = CreateMyClass;
MyClass* a = creator_function();

Then, lambda function seems like:

std::function<MyClass* ()> creator_function = []() { return new MyClass; };
MyClass* a = creator_function();

Finally, this would also work:

MyClass* a = []() { return new MyClass; }();
ALittleDiff
  • 1,191
  • 1
  • 7
  • 24