Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22202

Why is a function that only returns a stateful lambda compiled down to any assembly at all?

$
0
0

The following non-templated (or is it?) function returning a non-generic, stateful lambda,

auto foo(double a) {    return [a](double b) -> double {        return a + b;    };}

compiled down to this with GCC or Clang. Why?

foo(double):        ret

I would expect it generates no output at all.


The origin of the question

I don't even remeber why I started writing the snippet above, but anyway...

Initially I thought it should have compiled to something slightly longer, as I was expecting to see an add instruction at least.

But then I realized that the foo above, cannot be just compiled alone, in a cpp, and then linked against another TU where it's used, because I can't even write a declaration-only for it!

So I get to the point that the only reason to write that function in a non-header file, is that it is used in that non-header file, at which point there's the compiler can presumably inline it wherever it's used.

But if that's the case... then why copiling foo down to anything, if it's the only thing in the TU? There's nothing to link against, so why is any output generated at all for it?


Using a struct+operator() doesn't change anything, as this

struct Bar {    double a;    double operator()(double b) const {        return a + b;    }};Bar bar(double a) {    return Bar{a};}

generates the same ret-only code, which is also obvious in hindsight, as there's no way to even link against this bar function from other TUs, if Bar is hidden in the cpp file.


Viewing all articles
Browse latest Browse all 22202

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>