Home > Article > Backend Development > When Does \"auto\" Deduce a Value or a Reference in C 11?
Understanding C 11 "auto" Semantics
In C 11, the "auto" keyword allows for automatic type deduction. However, determining whether it resolves to a value or a reference can sometimes be ambiguous.
Type Deduction Rules:
The rule for type deduction in "auto" is straightforward: it is based on how the object is declared.
For instance:
<code class="cpp">int i = 5;</code>
If we declare:
<code class="cpp">auto a1 = i; // value auto &a2 = i; // reference</code>
a1 will be deducted as a value type (int), while a2 will be deducted as a reference type (int&).
Ambiguous Cases:
Consider the following examples:
<code class="cpp">const std::shared_ptr<Foo>& get_foo(); auto p = get_foo(); // Copy or reference?</code>
get_foo returns a reference, but p is declared as an "auto." In this case, auto will deduce the type of p to be a reference to Foo.
<code class="cpp">static std::shared_ptr<Foo> s_foo; auto sp = s_foo; // Copy or reference?</code>
s_foo is a static instance of a shared pointer to Foo. sp is declared using "auto," so it will be deducted as a shared pointer to Foo.
<code class="cpp">std::vector<std::shared_ptr<Foo>> c; for (auto foo: c) { // Copy for every loop iteration?</code>
Here, "auto" will iterate through the vector, deducing the type of foo to be a shared pointer to Foo. This means that a new temporary shared pointer is created for each iteration.
Demonstration:
The following code demonstrates these concepts:
<code class="cpp">#include <typeinfo> #include <iostream> template< typename T > struct A { static void foo(){ std::cout << "value" << std::endl; } }; template< typename T > struct A< T&& > { static void foo(){ std::cout << "reference" << std::endl; } }; float& bar() { static float t=5.5; return t; } int main() { int i = 5; int &r = i; auto a1 = i; auto a2 = r; auto a3 = bar(); A<decltype(i)>::foo(); // value A<decltype(r)>::foo(); // reference A<decltype(a1)>::foo(); // value A<decltype(a2)>::foo(); // value A<decltype(bar())>::foo(); // reference A<decltype(a3)>::foo(); // value }</code>
Output:
value reference value value reference value
The above is the detailed content of When Does \"auto\" Deduce a Value or a Reference in C 11?. For more information, please follow other related articles on the PHP Chinese website!