auto return types in C++ function vs specifying return type

592 Views Asked by At

In my work's codebase, I see the following

class custom {
  auto set_data_type(custom_type_t type_t) -> custom & {
    // set some stuff
    // return *this;
  }
}

Why can't we simply just do

class custom {
  custom & set_data_type(custom_type_t type_t) {
    // set some stuff
    // return *this;
  }
}

What is the point of using auto in this case when you already know the return type and already wrote it out in the ->... place?

It seems auto would only be beneficial if it is used with decltype(arg) and where arg may have varying return types?

3

There are 3 best solutions below

0
Jarod42 On

I would say style.

Moreover, it allows to be consistent in any contexts,

  • simple one (as this one),
  • more useful ones ("complex" decltype(arg) , scoping (-> iterator instead of typename C::iterator)
  • or required one (lambda).
0
Julien Lopez On

To me the most use of this feature is when you're using nested type when defining a function body in a cpp file:

class MyLongClassName
{
  using ANestedType = ...;

  ANestedType myFunction();
}

When you implement to function body, this syntax avoid some repetition:

MyLongClassName::ANestedType MyLongClassName::myFunction()
{ ... }

versus

auto MyLongClassName::myFunction() -> ANestedType
{ ... }
0
BorisV On

I believe, "auto" should not be used at all. IMHO, this is ugly sibling of void*; it hides types from programmer, while it is better to know exactly what type is used; this makes one's programming style clumsy, confuses and invites bugs. While the only "reasonable" use of this is typename "shortening", it is actually ridiculous, because short type names don't need to replaced, and for long names there is another keyword. IMHO.