1

For example, in:

  virtual auto create_obj() -> std::unique_ptr<Base>
  {
    return std::unique_ptr<Base>{};
  }

What does -> signify ? Since the return type is specified as auto, why is it necessary ?

Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190

1 Answers1

3

It is referred to as trailing return type, it is simply another way to specify the return type of a function.

One situation where it is useful is returning a function pointer from a function. Here is the "standard" syntax:

void yoyo(){
    std::cout << "yoyo!\n";
}

void(*my_fn())(){
    return yoyo;
}

Versus the more "modern" syntax:

auto my_fn() -> void(*)(){
    return yoyo;
}

Which is much easier to read.

P.S. The trailing return type can be used for function pointer declarations too:

auto yoyo(){ std::cout << "yoyo!\n"; }

auto yoyo_fn() -> void(*)(){ return yoyo; }

auto too_far() -> auto(*)() -> void(*)(){ return yoyo_fn; }

Which is pretty contrived, but is much easier to read than if I had to write in the traditional syntax!

RamblingMad
  • 5,332
  • 2
  • 24
  • 48
  • But why use auto then ? May as well have specified the return type the usual way... just seems like unnecessary typing. Surely there must be more to it ? – Rahul Iyer Sep 27 '16 at 10:44
  • @John in your example it is pointless, but I will include an example where it is useful. – RamblingMad Sep 27 '16 at 10:44
  • 2
    @John It's just a matter of preference. I personally write `auto main() -> int` because it annoys people. – user703016 Sep 27 '16 at 10:46
  • @PatrickM'Bongo Do you just like typing ? Is this some kind of legacy thing that just didn't go away ? – Rahul Iyer Sep 27 '16 at 10:47
  • @John, no, it's a totally _new_ thing. See the duplicate question/answer. – Jan Hudec Sep 27 '16 at 10:48
  • @John I added a lil example where it helps readability – RamblingMad Sep 27 '16 at 10:59
  • omg. I'm going to have to write a new question to figure out what void(*my_fn())() means... Is that a typo ? How would you even refer to it - There is no function name... unless there is an extra pair of parenthesis around *my_fn... can you explain ? – Rahul Iyer Sep 29 '16 at 04:06