为什么下面的代码输出“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 Postconditions:
!*this
if any of the following hold: —f
is aNULL
function pointer. —f
is aNULL
pointer to member. —F
is an instance of the function class template, and!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 Postconditions:
!*this
if any of the following hold:—
f
is a NULL function pointer.[...]
由于fp
是一个空函数指针,上面这段应该保证在fp
初始化f
后,表达式 !f
计算结果为 true
。这反过来意味着,与 nullptr
的比较应该返回 true
(根据 § 20.8.11.2.6/1)。
这反过来意味着,这是一个错误。
关于c++ - std::function 构造函数和 nullptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16823501/