std :: function constructor和nullptr [英] std::function constructor and nullptr
问题描述
为什么下面的代码输出0作为输出?
Why does the following code prints "0" as the output?
#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。
I've tested it both with gcc 4.7.2 and MSVC-11.0.
我认为它应该打印1,因为标准的以下引用:
I think that it's should print "1" because of the following quote from the standard:
ISO / IEC 14882:2011
20.8.11.2.1 function construct / copy / destroy [func.wrap.func.con]
20.8.11.2.1 function construct/copy/destroy [func.wrap.func.con]
模板< class F>函数(F f);
模板< class F,class A& function(allocator_arg_t,const A& a,F f);
...
8 后置条件: !*
如果存在以下任何内容: - f
是一个 NULL
函数指针。 - f
是指向成员的 NULL
指针。 - F
是函数类模板的实例
,!f
8 Postconditions: !*this
if any of the following hold: — f
is a NULL
function pointer. — f
is a NULL
pointer to member. — F
is an instance
of the function class template, and !f
推荐答案
我认为这是一个错误。根据C ++ 11标准的第20.8.11.2.6 / 1节:
I think this is a bug. Per paragraph 20.8.11.2.6/1 of the C++11 Standard:
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 c
。
1 Returns: !f
.
因此,(f == nullptr)
应评估为 true
当且仅当!f
true 。然后,第20.8.11.2.1 / 8段规定:
Therefore, (f == nullptr)
should evaluate to true
if and only if !f
evaluates to true
. Then, paragraph 20.8.11.2.1/8 specifies:
template<class F> function(F f);
template <class F, class A> function(allocator_arg_t, const A& a, F f);
[...]
8 后置条件:!*
如果存在以下任何内容
8 Postconditions: !*this
if any of the following hold:
-
f
是一个NULL函数指针。
—
f
is a NULL function pointer.
。]
由于 fp
空函数指针,上述段落应保证在 f 从
fp
初始化之后,表达式!f
计算为 true
。这反过来意味着与 nullptr
的比较应该返回 true
(根据§20.8.11.2.6 / 1) 。
Since fp
is a null function pointer, the above paragraph should guarantee that after initialization of f
from fp
, the expression !f
evaluates to true
. Which in turn means, that the comparison with nullptr
should return true
(by § 20.8.11.2.6/1).
这反过来意味着这是一个错误。
Which in turns means, that this is a bug.
这篇关于std :: function constructor和nullptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!