【发布时间】:2018-10-30 10:49:52
【问题描述】:
我惊讶地发现这段代码可以编译:
#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();
}
https://wandbox.org/permlink/FH3PoiYewklxmiXl
这将调用Callable 的非常量调用运算符。相比之下,如果您执行const auto cf = counter; cf();,那么它会按预期出错。那么,为什么 std::function 似乎没有遵循 const 正确性?
【问题讨论】:
-
我认为你对什么是 const 什么不是。你的声明没有使
counterconst,它是具有const=delete的那个。 -
为什么会调用
const版本?
标签: c++ constants std-function