3 回答

TA貢獻1777條經(jīng)驗 獲得超3個贊
盡可能auto
在任何地方使用- 特別是const auto
這樣可以減少副作用。除了明顯的情況外,您不必擔心類型,但它們?nèi)匀粫槟M行靜態(tài)驗證,并且您可以避免重復。在auto
不可行的地方,您可以使用decltype
語義表達類型作為基于表達式的契約。您的代碼看起來會有所不同,但這將是一個積極的變化。

TA貢獻1813條經(jīng)驗 獲得超2個贊
我認為auto只要很難說第一眼看到如何寫類型就應(yīng)該使用關(guān)鍵字,但表達式右側(cè)的類型是顯而易見的。例如,使用:
my_multi_type::nth_index<2>::type::key_type::composite_key_type::
key_extractor_tuple::tail_type::head_type::result_type
獲取復合鍵類型boost::multi_index,即使你知道它是int。你不能只是寫,int因為它可以在將來改變。我會寫auto這個案子。
因此,如果auto關(guān)鍵字提高了特定情況下的可讀性,則使用它。auto當讀者明白哪種類型auto代表時,你可以寫。
這里有些例子:
auto foo = std::make_shared<Foo>(); // obvious
auto foo = bla(); // unclear. don't know which type `foo` has
const size_t max_size = 100;
for ( auto x = max_size; x > 0; --x ) // unclear. could lead to the errors
// since max_size is unsigned
std::vector<some_class> v;
for ( auto it = v.begin(); it != v.end(); ++it )
// ok, since I know that `it` has an iterator type
// (don't really care which one in this context)
- 3 回答
- 0 關(guān)注
- 421 瀏覽
添加回答
舉報