没有遵循std :: function const的正确性

use*_*912 7 c++ const std-function

我惊讶地发现这段代码编译:

#include <functional>

struct Callable {
    void operator() () { count++; }
    void operator() () const = delete;
    int count = 0;
};

int main() {
    const Callable counter;
    // counter(); //error: use of deleted function 'void Callable::operator()() const'
    std::function<void(void)> f = counter;
    f();

    const auto cf = f;
    cf();

}
Run Code Online (Sandbox Code Playgroud)

https://wandbox.org/permlink/FH3PoiYewklxmiXl

这将调用非const调用运算符Callable.相比之下,如果你这样做,const auto cf = counter; cf();它会按预期出错.那么,为什么const正确性似乎没有被遵循std::function

Lig*_*ica 5

std::function添加了一个间接层,这个间接层不会通过constness 传递给callable.

我不确定为什么会这样 - 可能因为std::function需要一个可调用的副本而不需要保留副本const(事实上​​这可能会破坏赋值语义) - 我也不确定为什么你需要它.

(当然,直接调用operator()你恰好调用Callable并声明为的类型的对象const将需要一个const上下文,就像对任何其他对象一样.)

最佳做法是给予可调用a const operator()并将其保留.

tl; dr:是的,但不是一个bug,并不重要