c++ - std::function 构造函数和 nullptr

标签 c++ c++11

为什么下面的代码输出“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 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 段:

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/

相关文章:

c++ - C++中的条件运算符错误?

c++ - 为什么 sizeof(string) == 32?

c++ - 如何解锁 boost::upgrade_to_unique_lock(由 boost::shared_mutex 制成)?

c++ - 如何在C++11中优雅地解决二义性声明?

c++ - 在 C++ 中读取内存时出现段错误

c++ - c++ 编译器是否将多种算法合并为一个循环?

c++ - Boost.Bind'ing 成员函数并将其发布到 io_service

c++ - OpenGL 中的绘制顺序

python - 尝试将数据从 C++ 发送到 Python 并使用套接字 C++、C++ sendto() 和 python recvfrom() 工作但不是反向

c++ - 是否可以 std::move 本地堆栈变量?