[英]std::bind null function pointer
#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;
}
輸出為true。
我的期望是錯誤的,例如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
返回值:如果*this
存儲可調用的函數目標,則返回true
,否則返回false
。
換句話說,您的程序幾乎完全與此等效:
#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
包含一個可調用對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.