Function const std :: function wraps non-constant 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);
}

It const std::functionmay cause no const operator().

Conclusion:

12

The same thing happens if I put a mutablelambda, for example.test([x = 0]() mutable { ++x; });

How can it be?

Is it normal what a const std::functionmutable functor can wrap?

+4
source share
1 answer

Is it normal what a const std::functionmutable functor can wrap?

Unfortunately yes. std::function::operator()unconditionally qualifies as constit does not matter whether the wrapped mutated Callable. Some papers tried to solve this problem, but AFAIK nothing concrete was solved:

+6

Source: https://habr.com/ru/post/1688740/


All Articles