Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between function pointers, function object, and lambda functions? [closed]

Tags:

c++

c++11

I know each can be passed to another function. All of them seem to me like alternatives with subtle differences.

  1. function pointer: a pointer to a function

  2. function object: instance of a class that has overloaded the () operator; capable of acting as a function;

  3. lambda function: an anonymous function (newly introduced in C++11) that may be defined on the spot and that exists only during the lifetime of the statement of which it is a part

Because of the subtleties, I wonder which of the 3 choices would be the most appropriate in a given scenario. So, experts out there, kindly shed some light (on some selection criteria?) so that I could decide and use them in different scenarios.

like image 454
softwarelover Avatar asked Aug 30 '12 18:08

softwarelover


1 Answers

function object: An object f that you can call with the f(x) syntax. This includes function pointers, class objects having an overloaded operator() or conversion function to a function pointer/reference.

The Standard has a straight forward definition of it

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

In particular, a function or function reference is not a function object, even though they are callable entities. Some people confuse the term "function object" and take it to mean exclusively class type objects with an overloaded operator().

function pointer: An, err, pointer to a function

lambda function: I think you refer to the C++11 lambdas. These are not really functions, but special compiler-generated class type function objects that have an overloaded operator().

like image 93
Johannes Schaub - litb Avatar answered Oct 05 '22 23:10

Johannes Schaub - litb