3

Is there any difference between fn1 and fn2 and which one is better?

int half(int x) {return x/2;}

std::function<int(int)> fn1 = half;                    // function
std::function<int(int)> fn2 = &half;                   // function pointer


std::cout << "fn1(60): " << fn1(60) << '\n';
std::cout << "fn2(60): " << fn2(60) << '\n';
johnsam
  • 4,192
  • 8
  • 39
  • 58

1 Answers1

4

No, there isn't.

In the first construction, the function is passed to the std::function constructor as int (&) (int) - a reference to function.

In the second construction, the function is passed to the std::function constructor as int (*) (int) - a pointer to function.

The way the callable itself is stored inside the std::function object is implementation defined.

After construction, both fn1 and fn2 behave exactly the same, and there is no difference.

As for "which one is better" - I would prefer the reference version, as the sentence is less laden with operators, and anyway, my philosophy is to use pointers as little as possible, even if it's the safest pointer possible.

i alarmed alien
  • 9,412
  • 3
  • 27
  • 40
David Haim
  • 25,446
  • 3
  • 44
  • 78
  • Well, the problem with references is that they do not have regular value semantics, a reference data member makes an object not assignable to. – Maxim Egorushkin Oct 26 '17 at 10:29
  • @MaximEgorushkin. true, this is why I think one should use pointers, when he or she really really (but really) needs to (and not just because they learned bad C++ in university). one should always ask himself - can I write this piece of code without using pointers? – David Haim Oct 26 '17 at 10:31