Does/can C++ optimize away call to a function argument?

125 views Asked by At

Let's assume this function template:

template <typename F>
void foo(F&& f) {
  f("foo");
}

void to_optimize() {
  foo([](std::string_view s) {
      std::cout << s << std::endl;
    });
}

Does, or can, the compiler optimize the inline function away in cases like this? That is, to replace it effectively with just

void to_optimize() {
  std::cout << "foo" << std::endl;
}

?

2

There are 2 answers

1
Sam Varshavchik On

The C++ standard allows any optimization that has no observable effects. As described, optimizing out the function call will have no observable effect. The C++ program has no means of determining whether an additional function call occurred here.

So, yes, a C++ compiler can optimize out the function call. Whether or not it does depends on the compiler and the compiler configuration parameters.

4
Petr On

@PepijnKramer's comment pointed me to where I could explore this myself (with a slighly simplified example) - Clang with -O2: https://godbolt.org/z/YEb8vjYev. Indeed the compiler completely optimizes away the function call.

enter image description here

#include <iostream>

#ifdef AS_FUNCTOR
template <typename F>
void foo(F&& f) {
  f(42);
}

void to_optimize() {
  foo([](int s) {
      std::cout << s;
    });
}

#else  // AS_FUNCTOR

void to_optimize() {
  std::cout << 42;
}
#endif  // AS_FUNCTOR