为什么以下代码打印"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';
}
Run Code Online (Sandbox Code Playgroud)
我用gcc 4.7.2和MSVC-11.0测试了它.
我认为它应该打印"1",因为标准的以下引用:
ISO/IEC 14882:2011
20.8.11.2.1 function construct/copy/destroy [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
是NULL
函数指针.-f
是NULL
指向成员的指针.-F
是函数类模板的实例,和!f
And*_*owl 15
我认为这是一个错误.根据C++ 11标准的第20.8.11.2.6/1段:
Run Code Online (Sandbox Code Playgroud)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 返回:
!f
.
因此,(f == nullptr)
应该评估true
当且仅当!f
评估为true
.然后,第20.8.11.2.1/8段规定:
Run Code Online (Sandbox Code Playgroud)template<class F> function(F f); template <class F, class A> function(allocator_arg_t, const A& a, F f);
[...]
8 后置条件:
!*this
如果满足以下任何条件:-
f
是一个NULL函数指针.[...]
由于fp
是一个空函数指针,上面的段落应该保证在初始化f
from之后fp
,表达式!f
求值为true
.这反过来意味着,nullptr
应该返回的比较true
(通过§20.8.11.2.6/ 1).
这反过来意味着,这是一个错误.