C 11 "auto" Type Deduction: Resolving Reference vs. Value
In C 11, the "auto" keyword provides a convenient way to automatically deduce the type of a variable. However, when using "auto," it's essential to understand the rules that determine whether it resolves to a value or a reference.
Type Deduction Rules for "auto":
The fundamental rule is that "auto" interprets the declaration of the variable itself, not the type it represents. Therefore, the following example clearly demonstrates that "auto" resolves to a value:
<code class="cpp">auto i = v.begin(); // Copy, as begin() returns an iterator by value</code>
However, in more complex scenarios, the distinction can be less apparent. Consider the following examples:
<code class="cpp">const std::shared_ptr<Foo>& get_foo(); auto p = get_foo(); // Copy or reference?</code>
In this case, "auto" deduces the type from the return type of get_foo() function, which is a reference to a std::shared_ptr
<code class="cpp">static std::shared_ptr<Foo> s_foo; auto sp = s_foo; // Copy or reference?</code>
Here, "auto" deduces the type from the declaration of s_foo, which is a static std::shared_ptr
<code class="cpp">std::vector<std::shared_ptr<Foo>> c; for (auto foo: c) { // Copy for every loop iteration?</code>
In this case, "auto" deduces the type from the iterator type of the vector. The iterator returns std::shared_ptr
Conclusion:
The rule for "auto" type deduction is straightforward: it follows the declaration of the variable itself. To resolve to a reference, use an ampersand in the declaration (auto &ref = ...). Otherwise, "auto" will deduce a value type.
The above is the detailed content of When using \'auto\' in C 11, how does it determine whether a variable is a reference or a value?. For more information, please follow other related articles on the PHP Chinese website!