Home >Backend Development >C++ >When Does \'auto\' Deduce a Value vs. a Reference in C 11?

When Does \'auto\' Deduce a Value vs. a Reference in C 11?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 08:40:03837browse

When Does

C 11 "auto" Semantics

In C 11, the "auto" keyword allows for the compiler to automatically deduce the type of a variable. Understanding the rules for this deduction is crucial when determining whether "auto" will result in a value or a reference type.

Type Deduction for Value and Reference

The primary principle governing type deduction is that the type of "auto" is determined by the way it is declared. For instance:

<code class="cpp">int i = 5;
auto a1 = i;    // value
auto &a2 = i;  // reference</code>

In the above example, "a1" is deduced as an integer value, while "a2" is deduced as an integer reference.

Examples

1. Returning a Reference:

<code class="cpp">const std::shared_ptr<Foo>& get_foo();
auto p = get_foo();</code>

In this case, "auto" deduces a reference type because "get_foo()" returns a const reference.

2. Static Pointer:

<code class="cpp">static std::shared_ptr<Foo> s_foo;
auto sp = s_foo;</code>

Here, "auto" deduces a value type because "s_foo" is a static pointer, which is not a reference.

3. Looping Over a Container of Pointers:

<code class="cpp">std::vector<std::shared_ptr<Foo>> c;
for (auto foo : c) {</code>

In this loop, "auto" ensures that "foo" is deduced as a shared pointer to Foo. Each iteration creates a value copy of the pointer.

Conclusion

To summarize, the type deduction rules for "auto" in C 11 are straightforward. If the initialization expression is a value, "auto" deduces a value type. If the initialization expression is a reference, "auto" deduces a reference type. Understanding these rules is essential for effective use of "auto" and avoiding unexpected behavior.

The above is the detailed content of When Does \'auto\' Deduce a Value vs. a Reference in C 11?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn