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

你。 提交于 2019-12-10 13:49:41

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/47114936/a-const-stdfunction-wraps-a-non-const-operator-mutable-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!