Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A const std::function wraps a non-const operator() / mutable lambda

Consider the following example:

#include <iostream>
#include <functional>

struct A
{
    int i;
    void operator()() 
    {
        std::cout << ++i;
    }
};

void test(std::function<void()> const& fun)
{
    fun();
}

int main() {
    const std::function<void()> f{A{}};
    test(f);
    test(f);
}

Here, a const std::function is able to call a non-const operator().

Output:

12

The same happens if I supply a mutable lambda e.g. test([x = 0]() mutable { ++x; });

How can that be?

Is it normal that a const std::function may wrap a mutable functor?

like image 772
rustyx Avatar asked Nov 04 '17 19:11

rustyx


1 Answers

Is it normal that a const std::function may wrap a mutable functor?

Unfortunately, yes. std::function::operator() is unconditionally qualified as const and doesn't care whether or not the wrapped Callable is mutated. Some papers attempted to tackle this issue, but AFAIK nothing concrete was yet decided:

  • http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4348.html

  • http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0045r1.pdf

like image 123
Vittorio Romeo Avatar answered Nov 19 '22 00:11

Vittorio Romeo