我惊讶地发现这段代码编译:
#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?