我在VS2012中使用std::function遇到了一种奇怪的行为,我在网上找不到任何关于它的信息。
给定以下示例程序:
#include <functional>
#include <iostream>
typedef std::function< int()> fntype;
void foo(const fntype& fn)
{
try
{
if(fn)
fn();
else
std::cout << "fn is empty" << std::endl;
}
catch(const std::bad_function_call&)
{
std::cout << "fn threw anyways" << std::endl;
}
}
int main(int argc, char **argv)
{
// OK
std::function<int()> nothing;
foo(nothing);
// Fails
std::function<const int()> nothing2;
foo(nothing2);
return 0;
}
对 foo() 的第二次调用编译(即使返回类型的 const 与 fntype 不匹配。但是,if(fn) 的计算结果仍然为 true。
输出为:
fn 为空
FN还是扔了
注意:在调试器中,fn 在这两种情况下都显示为空
此行为不能使用 GCC (Coliru) 重现。在这里,生成预期的输出:
输出为:
fn 为空
fn 为空
这在标准库的VS2012实现中是一个问题吗?
有没有办法通过任一来解决此问题a) 让 fntype::运算符 bool() 在情况 2 或b) 由于签名不匹配而导致编译失败。
2012 年的错误,它似乎不会在 2013 年发生 查看实时 这个错误列表: Visual Studio 2013中修复了44个C++11个错误,还提到这是在2013年修复的,它说:
在某些情况下,转换可能会在 VS2012 由于函数对象在应该为空时不为空。 例如:
// JetPlane derives from Plane function<bool(JetPlane*)> plane_ready_func = function<bool(Plane*)>(); if (plane_ready_func) // should yield false but doesn't { plane_ready_func(nullptr); // gets called and throws bad_function_call }
std::function 的默认构造函数应创建一个空函数。
我发现了至少一个与上面的错误列表一致的错误报告。