为什么以下代码打印“0”作为输出?
#include <functional>
#include <iostream>
int main()
{
typedef void (*fp_t)();
fp_t fp = nullptr;
std::function<void()> f = fp;
std::cout << (f == nullptr) << '\n';
}
我已经使用 gcc 4.7.2 和 MSVC-11.0 对其进行了测试。
我认为它应该打印“1”,因为标准中引用了以下内容:
ISO/IEC 14882:2011
20.8.11.2.1 函数构造/复制/销毁 [func.wrap.func.con]
template<class F> function(F f);
template<class F, class A> function(allocator_arg_t, const A& a, F f);
...
8 后置条件: !*this
如果满足以下条件之一: —f
is a NULL
函数指针。 —f
is a NULL
指向成员的指针。 —F
是一个实例
函数类模板的,以及!f
我认为这是一个错误。根据 C++11 标准第 20.8.11.2.6/1 段:
template <class R, class... ArgTypes>
bool operator==(const function<R(ArgTypes...)>& f, nullptr_t) noexcept;
template <class R, class... ArgTypes>
bool operator==(nullptr_t, const function<R(ArgTypes...)>& f) noexcept;
1 Returns: !f
.
所以,(f == nullptr)
应该评估为true
当且仅当!f
评估为true
。然后,第 20.8.11.2.1/8 段规定:
template<class F> function(F f);
template <class F, class A> function(allocator_arg_t, const A& a, F f);
[...]
8 后置条件:!*this
如果满足以下任一条件:
— f
是一个NULL函数指针。
[...]
Since fp
是一个空函数指针,上面这段应该保证在初始化之后f
from fp
, 表达方式!f
评估为true
。这反过来意味着,与nullptr
应该返回true
(根据第 20.8.11.2.6/1 条)。
这反过来意味着,这是一个错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)