Are function pointers function objects in C++?

左心房为你撑大大i 提交于 2019-12-03 13:47:43

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

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.

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