0

In another topic someone suggested using

auto x = f();

instead of

T x = f();

(if the signature of f is T f()). They pointed out this prevents silent object slicing if someone happens to change f to U f(), where U descends from T.

It makes sense to me, but there might be other things in play that I am missing. So, which is better and why?

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
ricab
  • 2,697
  • 4
  • 23
  • 28
  • 4
    You may want to read [Herb Sutter's GotW #94 (Almost Always Auto)](http://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/). – syam Aug 28 '13 at 19:29

1 Answers1

1

One of the best advantaes of using auto in that context is, as Herb Sutter noticed at Almost Always Auto, that auto makes the usage of an API more mantenible. That is, the API can be modified/refactored without any necesary change in client code.
For example:

API v1.0

template<typename T>
T* abstract_factory::create();

API v2.0

template<typename T>
std::shared_ptr<T> abstract_factory::create();

Usage (Without auto)

 Foo* instance = abstract_factory::create<Foo>();

Client updates API library to v2.0

 Foo* instance = abstract_factory::create<Foo>(); //TYPE ERROR!!!

Update using auto

 auto instance = abstract_factory::create<Foo>(); //OK! type infered to std::shared_ptr<Foo>
Manu343726
  • 13,969
  • 4
  • 40
  • 75
  • 1
    Am I the only one that thinks "the API can be modified/refactored without any necesary change in client code." is a bad thing? – R. Martinho Fernandes Aug 29 '13 at 11:03
  • 1
    If things go ahead with a need to recompile, it's because the new thing you got from the new API has the same _duck type_ anyway, and therefore you shouldn't need to change the original code, unless your original code depended on a particular implementation or type (which should be avoided in most cases). In the latter case, you should specify the required type (e.g. `auto x = TypeINeed(f());`). Herb Sutter's article that was posted argues that well – ricab Aug 29 '13 at 12:19
  • Sorry, I meant "If things go ahead withOUT a need to recompile [...]" – ricab Aug 29 '13 at 12:33