문제

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?

도움이 되었습니까?

해결책

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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top