Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++11 require this lambda to be declared mutable?

People also ask

What is a mutable lambda?

The mutable keyword is used so that the body of the lambda expression can modify its copies of the external variables x and y , which the lambda expression captures by value. Because the lambda expression captures the original variables x and y by value, their values remain 1 after the lambda executes.

What is lambda function in C++11?

C++11 introduces lambdas allow you to write an inline, anonymous functor to replace the struct f . For small simple examples this can be cleaner to read (it keeps everything in one place) and potentially simpler to maintain, for example in the simplest form: void func3(std::vector<int>& v) { std::for_each(v.

How do you declare lambda in C++?

Creating a Lambda Expression in C++auto greet = []() { // lambda function body }; Here, [] is called the lambda introducer which denotes the start of the lambda expression. () is called the parameter list which is similar to the () operator of a normal function.

Why do we need lambda expressions in C++?

One of the new features introduced in Modern C++ starting from C++11 is Lambda Expression. It is a convenient way to define an anonymous function object or functor. It is convenient because we can define it locally where we want to call it or pass it to a function as an argument.


This isn't really about lambdas.

#include <functional>
#include <cstdlib>

int main() {
  const auto x = std::bind(std::puts, "hello");
  x();
}

This is accepted by GCC, but rejected by MSVC.

The standard is unclear on whether this is valid, IMO. The return value g of std::bind has an unspecified return type for which g(...) is valid and defined in terms of the cv-qualifiers of g, but the standard doesn't actually say that any operator() must be callable for const-qualified objects or references. It strongly implies that this is intended to be valid, because otherwise the reference to g's cv-qualifiers seems useless, but it doesn't actually say it is valid.

Because of that, I think MSVC's behaviour is not what the standard's authors intended, but it may nonetheless conform to what the standard requires.


This looks like a bug in the Visual Studio implementation of bind, returning a type with only a non-const function call operator. It should return a type that forwards all function calls to the bound function object, regardless of its own cv-qualifications.

To summarise the rather opaque language of C++11 20.8.9.1.2, function calls on the result of bind should be forwarded to the bound function object, and so should be allowed if calls on that object would be allowed. So it would be an error if the bound function object weren't callable if const; but here, being a function pointer, it is callable regardless of cv-qualifications.