Search code examples
c++constantsstd-function

Calling a std::function that I have a const reference too


I was somewhat confused to find that this code compiles and runs and prints 1 2 3:

#include <functional>
#include <iostream>

int main() {
    std::function<int()> counter = [i = 0]() mutable { i++; return i; };
    std::cout << counter() << std::endl;

    const auto& constRef = counter;
    std::cout << constRef() << std::endl;
    std::cout << counter() << std::endl;
}

It seems like a violation of const correctness to be able to call a non-const operator() of the underlying function when we only hold a const& to the std::function. Is there something I'm missing?

godbolt link


Solution

  • The only overload of it's call operator is

    std::function<R(Args...)>::operator()( Args... args ) const;
    

    It doesn't propagate const to it's target.