I was reading about closures on the net. I was wondering if C++ has a built-in facility for closures or if there is any way we can implement closures in C++?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Yes, C++11 has closures named lambdas.
In C++03 there is no built-in support for lambdas, but there is Boost.Lambda implementation.
Yes, This shows how you could implement a function with a state without using a functor.
I forgot the mutable keyword which introduced an undefined behaviour (clang version was returning a garbage value). As implemented, the closure works fine (on GCC and clang)
If you understand closure as a reference to a function that has an embedded, persistent, hidden and unseparable context (memory, state), than yes:
the next one modifies its state:
The inner state can not be referenced (accessed) from outside.
Depending on how you define it, a closure can contain a reference to more than one function or, two closures can share the same context, i.e. two functions can share the same persistent, ..., state.
Closure means not containing free variables - it is comparable to a class with only private attributes and only public method(s).
The latest C++ standard, C++11, has closures.
http://en.wikipedia.org/wiki/C%2B%2B11#Lambda_functions_and_expressions
http://www.cprogramming.com/c++11/c++11-lambda-closures.html
I suspect that it depends on what you mean by closure. The meaning I've always used implies garbage collection of some sort (although I think it could be implemented using reference counting); unlike lambdas in other languages, which capture references and keep the referenced object alive, C++ lambdas either capture a value, or the object refered to is not kept alive (and the reference can easily dangle).