gpt4 book ai didi

c++ - std::bind 空函数指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:48:56 33 4
gpt4 key购买 nike

#include <iostream>
#include <functional>

typedef int(*SumFptr)(int,int);

int main()
{

SumFptr ptr = nullptr;
std::function<int(int)> func = std::bind(ptr, std::placeholders::_1, 42);
std::cout << (func ? "true" : "false") << std::endl;

return 0;
}

输出为真。

我的期望是错误的,比如 std::function{nullptr}。它是错误还是正确的行为,我可以在哪里阅读它?

最佳答案

std::function 应该如何知道构造它的对象包含一个空指针?

就它而言它有一个可调用对象,它不知道它是一个包含空指针的可调用对象(如果调用它会崩溃)。

当您构造 std::function{nullptr} 时,它知道它没有可调用对象,并且其行为与调用默认构造函数完全一样。 std::function{ anything_else } 导致它存储 anything_else 并且除非它是空指针(不是包装空指针的对象!)将认为自己有一个目标对象。

http://en.cppreference.com/w/cpp/utility/functional/function/operator_bool

std::function::operator bool
Return value: true if *this stores a callable function target, false otherwise.

换句话说,您的程序几乎完全等同于此:

#include <iostream>
#include <functional>

using SumFPtr = int(*)(int,int);

struct BoundFunction {
SumFptr fptr;
int y;

int operator()(int x) const { return fptr(x, y); }
};

BoundFunction bind(SumFPtr fptr, int y)
{
return BoundFunction{fptr, y};
}

int main()
{
std::function<int(int)> func = bind(nullptr, 42);
std::cout << (func ? "true" : "false") << std::endl;
}

现在很明显,它当然会打印 "true",因为 std::function 包含一个可调用对象。

关于c++ - std::bind 空函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32885161/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com