Are function pointers function objects in C++?

守給你的承諾、 提交于 2019-12-12 07:36:52

问题


The C++ standard defines function objects as:

A function object type is an object type that can be the type of the postfix-expression in a function call. (link)

First I was thinking that function objects were functors, but then I realized that for a function pointer ptr of type P (not a function, but a function pointer), std::is_object_v<P> is true and can be called with the ptr(Args...) syntax.

I am right that function pointers are considered as function objects by the standard? And if they are not what part of the definition is not satisfied by function pointers?


回答1:


Yes, they are. The term "object" in C++ standard does not mean "object" in the OOP sense. An int is an object.




回答2:


Function pointer is what it sounds like: a pointer to function. As itself it's a storage containing a pointer object, which returns a callable of function type.

If you take time and read first chapters of standard, you 'll understand that any variable declaration declares some type of storage that contains objects. Those can be objects of primitive types or classes. Essentially in C++ anything that can be stored is object.

By declaring function pointer you create storage that can store address of that function and operator() can be used

Anther type of callable closure can be created by lambda expression. They are not function objects, each expression creates a unique callable object, but captureless lambdas can be used as one, e.g. to assign it to a function pointer, e.g.

double (*square)(double) = [](double a)->double { return a*a; };

after this you can call it using expression like square(3.6);

For functions and lambda call operator operator() is supplied by language, by defining operator() for a class you create what people often call "functor", which is misnomer because actual functors in mathematics or such languages like Haskell do not store state. Result of lambda expression is a "functor" created by compiler, which stores states of captured objects.

Naming those objects callable might be a little misleading too, because as a concept in C++, a callable object is any object that can be used with INVOKE operation, which include pointers to data members even while no function calls happen.

it leaves only one option, if we can use function call with said object, it's a function object. It can be function, lambda expression, function object, function pointer, member function pointer with specified class instance ( obj.*memberptr or objptr->*memberptr - call of member function is very special) - they are function objects.



来源:https://stackoverflow.com/questions/49503229/are-function-pointers-function-objects-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!