0

I found a piece of code from a co-worker who no longer works for the same company as me, so I can't ask them myself.

This was the original code (1):

Class Foo {
  void bar(InType i, OutType* o);
};

void Foo::bar(InType i, OutType* o) {
  o = something();
  if (!o->valid()) throw Exception();
}

They changed it to (2):

Class Foo {
  OutType bar(InType i);
};

auto Foo::bar(InType i) -> OutType {
  OutType o;
  o = something();
  if (!o->valid()) throw Exception();
  return o;
}

This appears the same as (3):

Class Foo {
  OutType bar(InType i);
};

OutType Foo::bar(InType i) {
  OutType o;
  o = something();
  if (!o->valid()) throw Exception();
  return o;
}

I understand that #2 is a member variable that is a lambda, but what do this gain? The lambda is still called just like a regular function syntactically.

Is there a real reason to use #2 instead of #3?

TheBat
  • 1,006
  • 7
  • 25
  • 4
    A lambda has the form `[](){}`. You don't have that here. What you are seeing in #2 is called a trailing return type – NathanOliver Jun 08 '21 at 21:16
  • 1
    @NathanOliver Thanks for the keyword, now I can do some more reading. That explains why I couldn't find any lambda usage like this. – TheBat Jun 08 '21 at 21:18
  • 3
    No worries. It's hard to search when you don't even know the search terms. FWIW, I googled *function with auto and arrow after it c++* to get the dupe target. That might help your google-fu in the future. – NathanOliver Jun 08 '21 at 21:19

0 Answers0