问题描述
我使用来自C ++ 11库的标准函数包装器,我看到一些奇怪的行为与它的布尔运算符。如果我创建一个 std :: function
对象,布尔运算符返回false。如果我将 nullptr
分配给对象,然后再次检查,这仍然是真的。问题出现时,我分配一个void指针,我已经转换为函数指针。考虑以下程序:
I'm using the standard function wrapper from the C++11 library, and I am seeing some strange behavior with its boolean operator. If I create a std::function
object the boolean operator returns false. This is still true if I assign nullptr
to the object and check again. The problem appears when I assign it a void pointer which I have cast into a function pointer. Consider the following program:
#include <functional>
#include <iostream>
void* Test() {
return nullptr;
}
int main(int argc, char* argv[]) {
std::function<void()> foo;
std::cout << !!foo << std::endl;
foo = nullptr;
std::cout << !!foo << std::endl;
foo = reinterpret_cast<void(*)()>(Test());
std::cout << !!foo << std::endl;
return 0;
}
我期望输出的是 0 0 0
,但结果是 0 0 1
(请参阅)。任何人都可以解释为什么当布尔运算符包含一个null,不可调用的函数指针时返回true?还请提及一个解决方法,以检查 std :: function
What I expect as output is 0 0 0
but the result is 0 0 1
(see demo). Can anyone explain why the boolean operator returns true when it contains a null, non-callable function pointer? And please also mention a workaround to check for nullptr
in std::function
注意:我已经尝试检查目标是否为null( foo.target< void *>()== nullptr
)使用布尔运算符,但似乎无论函数对象包含什么,目标总是空(即使当函数对象是完全精细的被调用)。
NOTE: I've already tried checking if the target is null (with foo.target<void*>() == nullptr
) instead of using the boolean operator, but it seems as if no matter what the function object contains, the target is always null (even when the function object is perfectly fine with being called).
推荐答案
看起来像是一个错误。首先,这里有一个,不会播放任何具有投射的游戏:
Looks like a bug to me. First, here's a simplified example that doesn't play any games with casts:
#include <functional>
#include <iostream>
typedef void (*VF)();
VF Test() {
return nullptr;
}
int main(int argc, char* argv[]) {
std::function<void()> foo(Test());
std::cout << !!foo << std::endl;
return 0;
}
它仍然使用GCC打印1。不应该:
It still prints 1 with GCC. It shouldn't:
-
f
是NULL
函数指针。 -
f
是指向成员的NULL
指针。 -
code>是函数类模板的一个实例,
!f
f
is aNULL
function pointer.f
is aNULL
pointer to member.F
is an instance of the function class template, and!f
这篇关于std :: function的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!