Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

C++  Module 2 – Types, values and expressions

C++ auto, decltype and type aliases

What auto deduces from references and const, how decltype names the type of an expression, and how using makes aliases: every rule proved by the compiler.

  • Beginner
  • 20 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Use auto where the type is obvious or cannot be spelled
  • Predict what auto deduces from references and const
  • Predict what decltype gives for a name, a name in parentheses and a call
  • Detect the copies and proxies that auto makes where a reference or a value was meant
  • Write readable aliases with using

Before you start

What you’ll learn · Before you start

What you will learn

  • Use auto where the type is obvious or cannot be spelled
  • Predict what auto deduces from references and const
  • Predict what decltype gives for a name, a name in parentheses and a call
  • Detect the copies and proxies that auto makes where a reference or a value was meant
  • Write readable aliases with using

Before you start

On this page

for (auto p : prices) p *= 2; compiles and runs, and the prices 40, 25 and 60 stay exactly as they were: each p was a copy. auto in a declaration tells the compiler to take the variable’s type from its initializer: auto n = 7; makes n an int. It removes long type names, it is the only way to declare a variable whose type cannot be written, such as a lambda, and it never leaves a variable uninitialised. But it type deduction: The compiler working out a type from an initializer or an argument instead of reading it from the declaration, as it does for auto, decltype(auto) and the parameters of function templates. the type of the value, so it drops references and the const of the initializer itself: auto x = some_reference; makes a copy. Write auto& or const auto& when you want a reference.

decltype(expr) gives the type of an expression exactly as declared, references and const included. using Name = Type; creates an alias, a second name for an existing type, and also works for templates. Each deduction below is shown on Apple clang 21 and GCC 16, by a static_assert or by what the program prints.

auto takes the type of the value

Each line below declares a variable with auto, and a static_assert beneath states its type; if any statement were wrong, the file would not compile. std::is_same_v<A, B> is true exactly when A and B are the same type.

deduction.cpp C++
// What auto deduces, checked by the compiler:
// each static_assert stops the build if the type is not the one it names.
#include <print>
#include <string>
#include <type_traits>
#include <vector>

int main() {
    int count = 7;
    const int limit = 10;
    int& ref = count;
    const int& cref = limit;
    const int* p = &limit;
    int scores[3] = {90, 75, 60};
    std::vector<std::string> names{"Asha", "Ravi"};

    auto a = count;        // int
    auto b = limit;        // int: the const of the variable itself is dropped
    auto c = ref;          // int: a copy, the reference is dropped
    auto d = cref;         // int: both dropped
    auto e = p;            // const int*: a pointer to const keeps that const
    auto f = scores;       // int*: an array decays to a pointer to its first element
    auto g = "chai";       // const char*: a string literal is an array of const char
    auto h = names[0];     // std::string: a copy of the element
    auto i{5};             // int (since C++17)
    auto j = {5};          // std::initializer_list<int>, not int

    static_assert(std::is_same_v<decltype(a), int>);
    static_assert(std::is_same_v<decltype(b), int>);
    static_assert(std::is_same_v<decltype(c), int>);
    static_assert(std::is_same_v<decltype(d), int>);
    static_assert(std::is_same_v<decltype(e), const int*>);
    static_assert(std::is_same_v<decltype(f), int*>);
    static_assert(std::is_same_v<decltype(g), const char*>);
    static_assert(std::is_same_v<decltype(h), std::string>);
    static_assert(std::is_same_v<decltype(i), int>);
    static_assert(std::is_same_v<decltype(j), std::initializer_list<int>>);

    c = 100;  // changes the copy only, not count
    std::println("a={} b={} c={} d={} *e={} f[0]={}", a, b, c, d, *e, f[0]);
    std::println("g={} h={} i={} j.size()={} count={}", g, h, i, j.size(), count);
}
Ten deductions, each checked by static_assert Python · deduction_session.py
from session import run

run("""
clang++ --version | head -n 1
clang++ -std=c++23 -Wall -Wextra deduction.cpp -o deduction && ./deduction
g++-16 --version | head -n 1
g++-16 -std=c++23 -Wall -Wextra deduction.cpp -o deduction && ./deduction
""")

Output

$ clang++ --version | head -n 1
Apple clang version 21.0.0 (clang-2100.3.34.2)
$ clang++ -std=c++23 -Wall -Wextra deduction.cpp -o deduction && ./deduction
a=7 b=10 c=100 d=10 *e=10 f[0]=90
g=chai h=Asha i=5 j.size()=1 count=7
$ g++-16 --version | head -n 1
g++-16 (Homebrew GCC 16.2.0) 16.2.0
$ g++-16 -std=c++23 -Wall -Wextra deduction.cpp -o deduction && ./deduction
a=7 b=10 c=100 d=10 *e=10 f[0]=90
g=chai h=Asha i=5 j.size()=1 count=7

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 deduction_session.py

The file builds on both compilers, so all ten statements hold. The rules behind them:

  • The reference is dropped. c and d come from references, but they are new int variables holding copies: after c = 100;, count is still 7.
  • top-level const: A const that applies to an object itself, as in const int or int* const, rather than to what a pointer or a reference leads to. auto drops it, because the new variable is a separate object. is dropped. b is a plain int although limit is const int: const describes the variable limit, and b is a different variable. A const that belongs to the type pointed to is kept, so e is const int*: it still may not change limit through the pointer.
  • Arrays become pointers. f is int*, a pointer to scores[0], and g, from a string literal, is const char*. Neither copies the array.
  • Braces need care. Since C++17 auto i{5}; is an int, but auto j = {5}; is a std::initializer_list<int>, a list with one element, which is rarely what was meant.

The diagram follows one initializer, a const int&, down both paths: auto drops the reference and then the const, while auto& keeps both.

From const int& cref, auto drops the reference and then the top-level const, giving int; auto& keeps both, giving const int&.const int& cref = limit;(the initializer)drop the reference:const intdrop the top-level const:intauto x = cref;x is an int, a copyauto& r = cref;r is a const int&autoauto&

What auto and auto& deduce from a const reference

Text description of the diagram

The diagram starts from one initializer, const int& cref = limit;, and follows two arrows.

  • The arrow labelled auto goes down through two steps. First the reference is dropped, which leaves const int. Then the top-level const is dropped, which leaves int. So auto x = cref; makes x an int, a copy of the value.
  • The arrow labelled auto& goes to auto& r = cref;. With the & written out, nothing is dropped: r is a const int&, a reference to the same object that still cannot be changed through r.

Step through six of the ten declarations, one at a time, and watch the type change at each stage, from the reference that goes first to the array-to-pointer conversion: The implicit conversion of an array to a pointer to its first element, which happens in most uses of an array, such as auto f = scores;. The pointer no longer carries the array's length. that turns scores into an int*:

Interactive · stage by stage What auto does to the type of six initializers from deduction.cpp Step through one declaration at a time. Each stage shows the type the initializer has when it gets there, or why its rule changes nothing.
What auto does to the type of six initializers from deduction.cpp, step 6 of 6. Showing the initializer's type ({5} after an =), drop a reference (not used), drop a top-level const (not used), arrays become pointers (not used), the variable's type (initializer_list<int>). In focus: the initializer's type, the variable's type.the initializer's type{5} after an =drop a referencenot useddrop a top-level constnot usedarrays become pointersnot usedthe variable's typeinitializer_list<int>

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. auto c = ref;. ref is an int& bound to count. The reference is dropped first, so c is a new int holding a copy of 7: after c = 100; the program still printed count=7.
  2. auto d = cref;. cref is a const int& bound to limit. Dropping the reference leaves const int, and that const belongs to d itself, so it goes too: d is a plain int that may change.
  3. auto e = p;. p is a const int*. Here the const belongs to the int that p points at, not to p, so it is not top-level and auto keeps it: e is a const int*, and *e printed 10.
  4. auto f = scores;. scores is an array of 3 ints. auto cannot copy an array, so the array becomes a pointer to its first element: f is an int*, and f[0] printed 90.
  5. auto g = "chai";. A string literal is an array of const char, 5 of them with the final zero. The array becomes a pointer, and the const of the characters stays: g is a const char*.
  6. auto j = {5};. With = and braces, auto deduces a std::initializer_list<int> before any of these rules apply: j is a list with 1 element, as j.size() printed. auto i{5}; without the = is an int.

Every type in the figure is one of the static_assert lines of deduction.cpp, so the compiler has already checked each stage of it.

Key idea

auto makes a new variable from the value: the reference and the const of the initializer itself are dropped, a const behind a pointer stays, an array becomes a pointer, and = {…} makes a std::initializer_list.

Checkpoint

Check: What auto drops from an initializer

  1. Question 1 of 2 q is a constant pointer: it may not be moved, but the int it points at may change. What does auto r = q; deduce?

    Read the code, then choose one answer.

    int count = 7;
    int* const q = &count;
    auto r = q;
    Show the answer: Question 1 of 2

    Answer: int*

    A const right of the * belongs to the pointer, which makes it top-level, like the const of const int limit. auto drops it, so r is an int* holding the same address as q.

  2. Question 2 of 2 names is a std::vector<std::string>. What is copy, and does the last line compile?

    Read the code, then choose one answer.

    const std::string& who = names[0];
    auto copy = who;
    copy += "!";
    A hint

    Drop the reference first, then any const that belongs to the object itself.

    Show the answer: Question 2 of 2

    Answer: A std::string, and the last line compiles: it changes the copy only

    who is a const std::string&. auto removes the reference, which leaves const std::string, and then that top-level const, which leaves std::string: copy += "!" compiles and leaves names[0] as it was.

auto& and const auto& refer to the original; auto&& binds to anything

When you want the original object rather than a copy, say so. The difference matters most in range-based for: A loop of the form for (declaration : range) that runs its body once for each element of an array, a container or another range, in order, with no index to manage. auto copies each element; auto& refers to it. More in “C++ loops: while, do-while, for and range-for”:

references.cpp C++
// auto makes a copy; auto& and const auto& refer to the original.
// The loop that doubles nothing is a classic bug.
#include <print>
#include <string>
#include <vector>

int main() {
    std::vector<int> prices{40, 25, 60};

    for (auto p : prices) p *= 2;    // p is a copy of each element: the vector does not change
    std::println("after auto:  {}", prices);

    for (auto& p : prices) p *= 2;   // p refers to each element: the vector changes
    std::println("after auto&: {}", prices);

    const std::vector<std::string> cities{"Bengaluru", "Chennai", "Kolkata"};
    std::size_t letters = 0;
    for (const auto& city : cities) letters += city.size();  // reads each string without copying it
    std::println("{} letters in {} names", letters, cities.size());

    int x = 1;
    auto&& r1 = x;   // a forwarding reference: binds to x as int&
    auto&& r2 = 42;  // ... and to a temporary as int&&
    r1 = 5;
    std::println("x = {}, r2 = {}", x, r2);
}
Copies and references in loops Python · references_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra references.cpp -o references && ./references
g++-16 -std=c++23 -Wall -Wextra references.cpp -o references && ./references
""")

Output

$ clang++ -std=c++23 -Wall -Wextra references.cpp -o references && ./references
references.cpp:10:15: warning: variable 'p' set but not used [-Wunused-but-set-variable]
   10 |     for (auto p : prices) p *= 2;    // p is a copy of each element: the vector does not change
      |               ^
1 warning generated.
after auto:  [40, 25, 60]
after auto&: [80, 50, 120]
23 letters in 3 names
x = 5, r2 = 42
$ g++-16 -std=c++23 -Wall -Wextra references.cpp -o references && ./references
references.cpp: In function 'int main()':
references.cpp:10:15: warning: variable 'p' set but not used [-Wunused-but-set-variable=]
   10 |     for (auto p : prices) p *= 2;    // p is a copy of each element: the vector does not change
      |               ^
after auto:  [40, 25, 60]
after auto&: [80, 50, 120]
23 letters in 3 names
x = 5, r2 = 42

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 references_session.py

The first loop doubled copies, so the vector did not change. Both compilers warn that p is set but never used, which is the clue here; for a copy of a class type, such as a std::string, they stay silent, so the habit of writing references in loops matters more than the warning. auto& refers to each element, so the second loop changed them. const auto& reads each string without copying it, which is the usual way to loop over strings or other large objects that you only read.

Step through both loops over prices, one pass at a time. A dashed arrow means p is a copy of the element, a solid one that p is the element itself:

Interactive · step by step Two loops that double the prices, one pass at a time Step through both loops of references.cpp. The left column is the vector, the right one the loop variable p; a dashed arrow means p is a copy, a solid one that p is the element.
Two loops that double the prices, one pass at a time, step 6 of 6. Showing prices[0] (80), prices[1] (50), prices[2] (120), p, the loop variable (another name for prices[2]). In focus: p, the loop variable, prices[2].refers toprices[0]80prices[1]50prices[2]120p, the loop variableanother name for prices[2]

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. auto, pass 1. for (auto p : prices) makes p a new int, a copy of prices[0]. p *= 2 turns the copy into 80, while prices[0] is still 40.
  2. auto, pass 2. Each pass copies again: p starts as 25 and becomes 50, and the copy is destroyed at the end of the pass. The vector never sees the change.
  3. auto, pass 3. The last copy becomes 120. The program printed after auto: [40, 25, 60], and both compilers warned that p is set but never used.
  4. auto&, pass 1. for (auto& p : prices) makes p refer to prices[0] itself, so p *= 2 doubles the element: 40 becomes 80 inside the vector.
  5. auto&, pass 2. On the next pass p refers to prices[1], and 25 becomes 50. No int is copied: p is only a second name for the element.
  6. auto&, pass 3. prices[2] becomes 120, and the program printed after auto&: [80, 50, 120]. Every change reached the vector, because p was each element in turn.

The first loop made three copies, changed them and threw them away; the second wrote all three changes into the vector, because p was each element in turn.

auto&& is a forwarding reference: A reference written auto&&, or T&& in a template whose T is deduced, that binds to anything: it becomes an lvalue reference for a named variable and an rvalue reference for a temporary.: it binds to anything, as int& to a named variable (r1 changed x) and as int&& to a temporary such as 42. You will meet it in generic code; in everyday loops auto& and const auto& say more clearly what you mean.

A loop that changes copies

for (auto p : prices) p *= 2; doubles three copies and leaves prices at [40, 25, 60]. Write for (auto& p : prices) to change the elements, and for (const auto& city : cities) to read large elements without copying them.

Checkpoint

Check: auto&, const auto& and auto&&

  1. Question 1 of 2 What does stock hold after these two loops?

    Read the code, then choose one answer.

    std::vector<int> stock{3, 0, 5};
    for (auto s : stock) s += 10;
    for (auto& s : stock) s *= 2;
    A hint

    One of the two loops works on copies.

    Show the answer: Question 1 of 2

    Answer: [6, 0, 10]

    for (auto s : stock) makes s a copy, so s += 10 is lost at the end of each pass. for (auto& s : stock) makes s another name for each element, so s *= 2 turns 3, 0 and 5 into 6, 0 and 10.

  2. Question 2 of 2 What is the type of r in auto&& r = 42;?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: int&&

    auto&& is a forwarding reference: int& for a named int such as x, int&& for a temporary such as 42. The program printed r2 = 42.

decltype keeps what auto drops

decltype(e) gives the type of an expression without evaluating it, and it keeps what auto drops:

decltype_rules.cpp C++
// decltype(name) is the declared type of a variable;
// decltype((name)), with extra parentheses, is a reference.
#include <print>
#include <type_traits>
#include <vector>

int main() {
    int x = 0;
    const int c = 1;
    std::vector<int> v{1, 2, 3};

    static_assert(std::is_same_v<decltype(x), int>);
    // (x) is an expression that names an object
    static_assert(std::is_same_v<decltype((x)), int&>);
    // decltype keeps the const that auto drops
    static_assert(std::is_same_v<decltype(c), const int>);
    static_assert(std::is_same_v<decltype(v[0]), int&>);      // what operator[] returns
    static_assert(std::is_same_v<decltype(x + 1), int>);      // a computed value, not a reference

    auto copy = v[0];             // int
    decltype(auto) same = v[0];   // int&: the exact type of the initializer
    same = 10;
    copy = 20;
    std::println("v = {}, copy = {}", v, copy);
}
decltype rules, checked by static_assert Python · decltype_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra decltype_rules.cpp -o decltype_rules && ./decltype_rules
g++-16 -std=c++23 -Wall -Wextra decltype_rules.cpp -o decltype_rules && ./decltype_rules
""")

Output

$ clang++ -std=c++23 -Wall -Wextra decltype_rules.cpp -o decltype_rules && ./decltype_rules
v = [10, 2, 3], copy = 20
$ g++-16 -std=c++23 -Wall -Wextra decltype_rules.cpp -o decltype_rules && ./decltype_rules
v = [10, 2, 3], copy = 20

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 decltype_session.py

decltype(c) is const int, the declared type of c. decltype(v[0]) is int&, because operator[] returns a reference. The odd rule is the one with extra parentheses: decltype(x) names the variable and gives its declared type, int, while decltype((x)) is an expression that refers to an object, an lvalue: An expression that refers to an object with an identity, such as a named variable, (x) or v[0]. decltype gives a reference type, such as int&, for an lvalue that is not a plain name., and so gives int&.

decltype(auto) deduces like decltype instead of like auto: same became an int&, so same = 10; changed v[0], while copy = 20; changed only the copy. It is mostly used for function return types that must keep a reference.

Put side by side, the two forms agree on two of five initializers and differ on three. Every cell of this table is a static_assert in the program under it:

Initializer e auto a = e; gives decltype(e) gives
x, an int variable int int
(x), the same name in parentheses int int&
c, a const int variable int const int
v[0], an element of a std::vector<int> int, a copy int&
x + 1, a computed value int int
Both columns of the table, checked by static_assert C++ · auto_vs_decltype.cpp
// The same five initializers through auto and through decltype.
// Each static_assert is one cell of the table: the build stops if any cell is wrong.
#include <print>
#include <type_traits>
#include <vector>

int main() {
    int x = 0;
    const int c = 1;
    std::vector<int> v{7, 8, 9};

    // auto deduces the type of the value: a copy, never a reference, never const.
    auto a1 = x;
    auto a2 = (x);
    auto a3 = c;
    auto a4 = v[0];
    auto a5 = x + 1;
    static_assert(std::is_same_v<decltype(a1), int>);
    static_assert(std::is_same_v<decltype(a2), int>);
    static_assert(std::is_same_v<decltype(a3), int>);
    static_assert(std::is_same_v<decltype(a4), int>);
    static_assert(std::is_same_v<decltype(a5), int>);

    // decltype keeps what auto drops.
    static_assert(std::is_same_v<decltype(x), int>);
    static_assert(std::is_same_v<decltype((x)), int&>);
    static_assert(std::is_same_v<decltype(c), const int>);
    static_assert(std::is_same_v<decltype(v[0]), int&>);
    static_assert(std::is_same_v<decltype(x + 1), int>);

    a4 = 70;  // a copy: v[0] is still 7
    std::println("a1={} a2={} a3={} a4={} a5={} v[0]={}", a1, a2, a3, a4, a5, v[0]);
}

Output

a1=0 a2=0 a3=1 a4=70 a5=1 v[0]=7

Recorded with Apple clang version 21.0.0 (clang-2100.3.34.2) on macOS 26 arm64. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined auto_vs_decltype.cpp -o auto_vs_decltype && ./auto_vs_decltype

Both compilers built it with every warning turned into an error, and a4 = 70 left v[0] at 7: the auto column copies, and the decltype column keeps references and const.

Key idea

decltype of a plain name gives the type the name was declared with; any other expression that refers to an object, such as (x) or v[0], gives a reference.

Checkpoint

Check: decltype and decltype(auto)

  1. Question 1 of 2 double d = 2.5; Which declaration makes y a reference to d?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: decltype((d)) y = d;

    The parentheses rule of decltype: a plain name gives the declared type, while (d) is an lvalue expression and gives double&, as decltype((x)) gave int& in decltype_rules.cpp.

  2. Question 2 of 2 std::vector<int> v{1, 2, 3}; then decltype(auto) a = v[0]; and a = 10;. What is v[0] afterwards?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 10

    decltype(auto) deduces with decltype rules, and decltype(v[0]) is int&, so a refers to v[0] and the assignment changes the vector: decltype_rules.cpp printed v = [10, 2, 3].

auto keeps the proxy that std::vector<bool> hands out

auto takes whatever type the initializer has, even when that is not the type you had in mind.

std::vector<bool> stores its values as single bits, so flags[i] cannot return a bool&; it returns a small proxy object: An object returned in place of a reference, standing for an element that cannot be referred to directly, as std::vector<bool>::reference stands for one bit. It points into its container and is valid only while the container lives., std::vector<bool>::reference, that points into the vector. With auto, the variable is that proxy:

vector_bool.cpp C++
// std::vector<bool> packs its values into bits, so v[i] returns a small proxy object, not a bool&.
// auto then deduces the proxy type, which still points into the vector.
#include <print>
#include <type_traits>
#include <vector>

std::vector<bool> make_flags() { return std::vector<bool>(1000, false); }

int main() {
    std::vector<bool> flags(1000, false);

    auto first = flags[0];   // not a bool: a std::vector<bool>::reference
    static_assert(!std::is_same_v<decltype(first), bool>);
    first = true;            // writes into the vector
    std::println("flags[0] is now {}", static_cast<bool>(flags[0]));

    bool copy = flags[1];    // naming the type converts the proxy to a plain bool
    copy = true;
    std::println("flags[1] is still {}, copy is {}", static_cast<bool>(flags[1]), copy);

    auto dangling = make_flags()[0];  // a proxy into a temporary, destroyed at the end of this line
    std::println("reading it: {}", static_cast<bool>(dangling));  // reads freed memory
}
std::vector<bool> and auto, with AddressSanitizer Python · vector_bool_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined vector_bool.cpp -o vector_bool && ./vector_bool
g++-16 -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined vector_bool.cpp -o vector_bool && ./vector_bool
""")

Output

$ clang++ -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined vector_bool.cpp -o vector_bool && ./vector_bool
flags[0] is now true
flags[1] is still false, copy is true
=================================================================
==…==ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 8 at 0x… thread T0
    #1 in main vector_bool.cpp:22
0x… is located 0 bytes inside of 128-byte region [0x…,0x…)
freed by thread T0 here:
    #7 in main vector_bool.cpp:21
previously allocated by thread T0 here:
    #9 in make_flags() vector_bool.cpp:7
    #10 in main vector_bool.cpp:21
SUMMARY: AddressSanitizer: heap-use-after-free
[56 more lines of the report left out]
[exit status 134]
$ g++-16 -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined vector_bool.cpp -o vector_bool && ./vector_bool
flags[0] is now true
flags[1] is still false, copy is true
=================================================================
==…==ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 8 at 0x… thread T0
    #1 in main vector_bool.cpp:22
0x… is located 0 bytes inside of 128-byte region [0x…,0x…)
freed by thread T0 here:
    #5 in main vector_bool.cpp:21
previously allocated by thread T0 here:
    #5 in make_flags() vector_bool.cpp:7
    #6 in main vector_bool.cpp:21
SUMMARY: AddressSanitizer: heap-use-after-free
[50 more lines of the report left out]
[exit status 134]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 vector_bool_session.py

first = true; wrote into the vector, while the bool copy did not. (sanitizer: A compiler option, such as -fsanitize=address or -fsanitize=undefined, that builds extra checks into a program, so that memory errors and undefined behaviour are reported, with their source line, while it runs. More in “Finding memory bugs with AddressSanitizer and UBSan” reports run to dozens of lines, so the sessions keep the lines that name the error and this lesson’s own files, and write the memory addresses, which change on every run, as 0x….) The last two lines are the dangerous case: make_flags()[0] is a proxy into a temporary vector that is destroyed at the end of the line, so reading it reads freed memory. AddressSanitizer stops the program and names both lines, line 21 where the memory was allocated and freed and line 22 where it was read; without the sanitizer the program might print a plausible value. Write the type (bool b = flags[0];) when you want the value.

Step through the program and follow what each variable points into, up to the read that AddressSanitizer stops:

Interactive · step by step Where auto first and auto dangling point in vector_bool.cpp Step through the program. The left column holds the two vectors of bits, the right one the variables made from them; an arrow shows what a proxy points into.
Where auto first and auto dangling point in vector_bool.cpp, step 6 of 6. Showing flags: 1000 bits (bit 0 is now true), auto first = flags[0], bool copy = flags[1] (true, while flags[1] is false), make_flags() result (destroyed, its memory freed), auto dangling (reads freed memory). In focus: auto dangling, make_flags() result.points intocopied oncepoints intoflags: 1000 bitsbit 0 is now trueauto first = flags[0]a proxy, not a boolbool copy = flags[1]true, while flags[1] is falsemake_flags() resultdestroyed, its memory freedauto danglingreads freed memory

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. A proxy, not a bool. std::vector<bool> keeps each value as one bit, so flags[0] cannot return a bool&. It returns a std::vector<bool>::reference that points at bit 0, and auto keeps that proxy: the static_assert proves first is not a bool.
  2. Writing through it. first = true; writes through the proxy into the vector, and the program printed flags[0] is now true.
  3. Naming the type. bool copy = flags[1]; converts the proxy to a plain bool once. copy = true; changes only copy, and the program printed flags[1] is still false, copy is true.
  4. A proxy into a temporary. make_flags() returns a temporary vector whose bits fill a 128-byte block, allocated on line 7, and [0] hands out a proxy into it. auto dangling keeps the proxy.
  5. The end of line 21. The temporary vector is destroyed at the end of the full expression on line 21, and its 128 bytes are freed. dangling still points into them.
  6. Line 22 reads it. static_cast<bool>(dangling) reads the freed memory. AddressSanitizer stopped both builds with a heap-use-after-free report that names lines 21 and 22, and the run ended with exit status 134.

Neither compiler warned about line 21, and nothing on that line looks wrong: the type that auto deduced is the whole problem.

Checkpoint

Check: The proxy of std::vector<bool>

  1. Question 1 of 2 std::vector<bool> flags(8); What type does auto f = flags[0]; give f?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: std::vector<bool>::reference, a proxy for one bit

    The static_assert in vector_bool.cpp proves it: decltype(first) is not bool. first = true; then wrote through the proxy into the vector.

  2. Question 2 of 2 load() returns a new std::vector<bool> each time. Which read on the last line reads freed memory?

    Read the code, then choose one answer.

    bool a = load()[0];
    auto b = load()[0];
    std::vector<bool> kept = load();
    auto c = kept[0];
    std::println("{} {} {}", a, static_cast<bool>(b), static_cast<bool>(c));
    A hint

    Ask which vector each variable still points into when the last line runs.

    Show the answer: Question 2 of 2

    Answer: Reading b

    Only b points into a vector that no longer exists: a proxy is valid only while its vector lives, and writing the type, bool, copies the value out at once.

auto keeps the exact type of a literal or a size

Number types are the other surprise. A literal or an expression has a type of its own, and auto keeps it:

integer_auto.cpp C++
// auto takes the type of a literal or an expression exactly as it is,
// which is not always the type you wanted.
#include <cstddef>
#include <print>
#include <type_traits>
#include <vector>

int main() {
    auto small = 3'000;          // int
    auto big = 3'000'000'000;    // too big for int: long here, long long on Windows
    auto size = std::vector<int>(5).size();  // std::size_t, an unsigned type
    static_assert(std::is_same_v<decltype(small), int>);
    static_assert(std::is_same_v<decltype(big), long>);
    static_assert(std::is_same_v<decltype(size), std::size_t>);

    std::vector<int> v{3, 1, 4};
    for (auto i = 0; i < v.size(); ++i) {  // int i against an unsigned size: a mixed comparison
        std::print("{} ", v[i]);
    }
    std::println("| sizes in bytes: {} {} {}", sizeof small, sizeof big, sizeof size);
}
auto with literals and sizes Python · integer_auto_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra integer_auto.cpp -o integer_auto && ./integer_auto
g++-16 -std=c++23 -Wall -Wextra integer_auto.cpp -o integer_auto && ./integer_auto
""")

Output

$ clang++ -std=c++23 -Wall -Wextra integer_auto.cpp -o integer_auto && ./integer_auto
integer_auto.cpp:17:24: warning: comparison of integers of different signs: 'int' and 'size_type' (aka 'unsigned long') [-Wsign-compare]
   17 |     for (auto i = 0; i < v.size(); ++i) {  // int i against an unsigned size: a mixed comparison
      |                      ~ ^ ~~~~~~~~
1 warning generated.
3 1 4 | sizes in bytes: 4 8 8
$ g++-16 -std=c++23 -Wall -Wextra integer_auto.cpp -o integer_auto && ./integer_auto
integer_auto.cpp: In function 'int main()':
integer_auto.cpp:17:24: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   17 |     for (auto i = 0; i < v.size(); ++i) {  // int i against an unsigned size: a mixed comparison
      |                      ~~^~~~~~~~~~
3 1 4 | sizes in bytes: 4 8 8

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 integer_auto_session.py

3'000'000'000 does not fit in a 32-bit int, so the literal is a long, 8 bytes on 64-bit macOS and Linux. On Windows long has 4 bytes, so the same literal is a long long there. size() returns std::size_t, an unsigned type, while auto i = 0 makes an int, and the comparison of the two in the loop condition gets a -Wsign-compare warning from both compilers. In such a comparison the int is converted to the unsigned type, so a negative value would compare as a huge number. Declare the loop variable as std::size_t, or loop over the elements with for (int x : v).

The three variables of the program, with the sizes it printed on this 64-bit Mac, 4 8 8:

Initializer auto deduces Bytes here
3'000 int 4
3'000'000'000 long (long long on Windows) 8
std::vector<int>(5).size() std::size_t, unsigned 8

None of the three types is written in the program, and only the first is an int: read the type off the initializer before you trust auto with a number.

Checkpoint

Check: The types of literals and sizes

  1. Question 1 of 2 On 64-bit macOS or Linux, what does auto big = 3'000'000'000; deduce?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: long

    integer_auto.cpp checks it with static_assert and printed 8 for sizeof big. auto keeps whatever type the literal has, so the same line gives long here and long long on Windows.

  2. Question 2 of 2 std::vector<int> v{3, 1, 4}; Which loop header compiles without the -Wsign-compare warning both compilers gave?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: for (std::size_t i = 0; i < v.size(); ++i)

    The warning is about a signed loop variable compared with an unsigned size. Give the variable the size's type, or loop over the elements with for (int x : v) and need no index at all.

using gives a type a second name, not a new type

using Name = Type; gives an existing type a second name, a type alias: A second name for an existing type, made with using Name = Type; or typedef. It makes no new type, so values of the alias and of the original type mix freely.. It reads left to right, like an assignment, and unlike the older typedef it can also be a alias template: A type alias with template parameters, such as template <typename T> using Grid = std::vector<std::vector<T>>;, which typedef cannot write.:

aliases.cpp C++
// using gives an existing type a second name. It does not create a new type,
// so mixing up two aliases of the same type still compiles.
#include <cstdint>
#include <map>
#include <print>
#include <string>
#include <type_traits>
#include <vector>

using Score = std::int32_t;
// much shorter to write than the type it names
using Marks = std::map<std::string, std::vector<Score>>;

template <typename T>
// an alias template: typedef cannot do this
using Grid = std::vector<std::vector<T>>;

typedef std::int32_t OldScore;                            // the older way to write the same alias

using Metres = double;
using Seconds = double;

int main() {
    static_assert(std::is_same_v<Score, std::int32_t>);
    static_assert(std::is_same_v<Score, OldScore>);

    Marks marks{{"Asha", {78, 91}}, {"Ravi", {64}}};
    Grid<char> board(2, std::vector<char>(3, '.'));
    board[1][2] = 'X';

    const Metres distance = 1500.0;
    const Seconds time = 300.0;
    const double nonsense = distance + time;  // compiles: both are just double

    std::println("{} students, board {}x{}, row 1 = {}, distance + time = {}", marks.size(), board.size(),
                 board[0].size(), std::string(board[1].begin(), board[1].end()), nonsense);
}
Aliases and alias templates Python · aliases_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra aliases.cpp -o aliases && ./aliases
g++-16 -std=c++23 -Wall -Wextra aliases.cpp -o aliases && ./aliases
""")

Output

$ clang++ -std=c++23 -Wall -Wextra aliases.cpp -o aliases && ./aliases
2 students, board 2x3, row 1 = ..X, distance + time = 1800
$ g++-16 -std=c++23 -Wall -Wextra aliases.cpp -o aliases && ./aliases
2 students, board 2x3, row 1 = ..X, distance + time = 1800

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 aliases_session.py

Marks saves writing std::map<std::string, std::vector<std::int32_t>> everywhere, and Grid<char> is a std::vector<std::vector<char>>. The C++ Core Guidelines recommend using over typedef (rule T.43) for these reasons.

An alias is not a new type. Score and std::int32_t are the same type, which the first static_assert proves, and so are Metres and Seconds: adding a distance to a time compiled and printed 1800. When two kinds of value must never be mixed, make them different types: small structs (a later module) or an enum class.

Step through the six names the program declares and the types behind them:

Interactive · step by step The aliases of aliases.cpp and the types they name Step through the aliases. The left column holds the names the program declares, the right one the types the compiler sees; an arrow means the two are the same type.
The aliases of aliases.cpp and the types they name, step 5 of 5. Showing Score, OldScore, Marks, Grid<char>, Metres, Seconds, std::int32_t, std::map<…>, vector<vector<char>>, double. In focus: double.namesnamesnamesnamesnamesnamesScoreusingOldScoretypedef, the older formMarksusingGrid<char>an alias templateMetresusingSecondsusingstd::int32_ta fixed-width integerstd::map<…>string to vector<Score>vector<vector<char>>std:: left out heredoubleone type for both

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Score and OldScore. using Score = std::int32_t; and the older typedef std::int32_t OldScore; give one type two more names. The two static_asserts prove that Score, OldScore and std::int32_t are the same type.
  2. A long name made short. Marks saves writing std::map<std::string, std::vector<std::int32_t>> wherever the marks of a class are passed around. marks.size() printed 2 students.
  3. An alias template. Grid is an alias template, which typedef cannot write: Grid<char> is std::vector<std::vector<char>>. The program printed board 2x3 and row 1 = ..X.
  4. Two names for double. Metres and Seconds both name double. distance + time compiled on both compilers without a warning and printed 1800: the aliases did not stop a distance being added to a time.
  5. No new type. An alias is never a new type, so it cannot catch a mix-up of units. Values that must not mix need types of their own, such as small structs or an enum class.

Two arrows end at std::int32_t and two at double: the compiler sees one type in each place, which is why the static_assert lines hold and why 1800 printed without a complaint.

Key idea

using adds a name, never a type: it shortens long names and makes alias templates possible, but an alias and its type mix freely, so metres and seconds still add up without a word.

Checkpoint

Check: Aliases made with using

  1. Question 1 of 2 Which of the two calls compile?

    Read the code, then choose one answer.

    using Id = std::int64_t;
    void ban(Id user);
    
    ban(std::int64_t{42});
    ban(7);
    Show the answer: Question 1 of 2

    Answer: Both: Id is std::int64_t, and 7 converts to it as to any std::int64_t

    using Id = std::int64_t; adds a name and nothing else, so both calls compile, exactly as distance + time compiled for Metres and Seconds.

  2. Question 2 of 2 Which declaration makes Pairs<int> mean std::vector<std::pair<int, int>>?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: template <typename T> using Pairs = std::vector<std::pair<T, T>>;

    Only using can declare an alias template: template <typename T> using Pairs = …; then Pairs<int> and Pairs<char> are the two vector types.

Write auto when the type is plain to see, and the type when it is the point

  • Use it when the type is already visible in the initializer (auto p = std::make_unique<Order>();, auto n = static_cast<int>(x);), when the type is long and adds nothing (iterators, map entries), and when it cannot be written at all, as for lambdas. The Core Guidelines give the same advice in rule ES.11.
  • Add & or const auto& whenever you mean the original object, especially in loops.
  • Write the type when the exact type is the point: integer widths, bool from std::vector<bool>, a value that must not narrow.

Your own declaration decides which form fits. Answer three questions about the variable you are writing: the table then rules out every form that would fail it, naming the program above that showed the failure:

Interactive · answer and compare auto, a reference, or the type written out? Answer the questions about the variable you are declaring. The table rules out the forms that cannot do what you need, with the reason, and marks the ones that fit with a caveat.
Must the code change the object it reads, such as each element of a vector?
Is each object large, such as a std::string, or small, such as an int?
Does the exact type matter, such as an integer width or a bool from std::vector<bool>?

Answer the questions above: the table then marks what fits your case and says why the rest does not.

Five ways to declare a variable against changing the original, copying and naming the exact type
Declaration Changes reach the original No copy of the object Says the exact type
auto Poor no: p *= 2 doubled copies, and prices stayed [40, 25, 60] Poor copies what it reads, a whole std::string for each name Poor keeps what the initializer is: a proxy, a long, a std::size_t
auto& Good yes: the same loop with auto& printed [80, 50, 120] Good no copy: p is another name for each element Mixed the type of the object, its const kept: const int& from cref
const auto& Poor no: it only reads, and an assignment through it does not compile Good no copy: the loop read 23 letters from 3 city names Mixed the type of the object, with const added
auto&& Good yes: auto&& r1 = x; then r1 = 5 changed x to 5 Good no copy: it binds to a variable, and to a temporary such as 42 Mixed int& for x, int&& for 42: correct, but hard to read in a loop
The type written out Mixed only when you write a reference: int& changes the original, int copies it Mixed a value type copies; a reference type does not Good yes: bool copy = flags[1] is a bool, never a proxy
How the answers decide
  • “Must the code change the object it reads, such as each element of a vector?” Yes, it changes it: rules out auto and const auto&. auto changes only its copy, as the first loop over prices showed, and const auto& refuses every change.
  • “Must the code change the object it reads, such as each element of a vector?” Yes, it changes it: adds a caveat to The type written out and auto&&. Both can change the original: the written type only when it is a reference such as int&, and auto&& says it less plainly than auto& in an everyday loop.
  • “Must the code change the object it reads, such as each element of a vector?” No, it only reads it and “Is each object large, such as a std::string, or small, such as an int?” Large, like a std::string: rules out auto. auto copies each large object it reads; const auto& read 23 letters from 3 city names without a single copy.
  • “Must the code change the object it reads, such as each element of a vector?” No, it only reads it and “Is each object large, such as a std::string, or small, such as an int?” Large, like a std::string: adds a caveat to auto&. auto& reads without copying too, but it also lets the code change what it should only read.
  • “Must the code change the object it reads, such as each element of a vector?” No, it only reads it and “Is each object large, such as a std::string, or small, such as an int?” Small, like an int: Copying a small value such as an int costs next to nothing, so auto is a fine way to read it.
  • “Does the exact type matter, such as an integer width or a bool from std::vector<bool>?” Yes, the type is the point: rules out auto and auto&&. auto keeps whatever the initializer is: a std::vector<bool>::reference, a long for 3,000,000,000, a std::size_t from size(). Write the type, as bool copy = flags[1] does.
  • “Does the exact type matter, such as an integer width or a bool from std::vector<bool>?” Yes, the type is the point: adds a caveat to auto& and const auto&. A reference made with auto still takes its type from the initializer; only a type you write yourself names it exactly.

In short: auto for small values you only read and for types that are long or cannot be written, auto& to change the original, const auto& to read large objects, and the type itself when the type is what matters.

Checkpoint

Check: Choosing auto, a reference or the type

  1. Question 1 of 2 A loop must raise each double in std::vector<double> prices by 5 %. Which header does it?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: for (auto& p : prices)

    To change the elements, the loop variable must be a reference to each of them, and auto& says exactly that.

  2. Question 2 of 2 A count is written into a file whose field is exactly 64 bits on every platform. Which declaration fits?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: std::int64_t count = 3'000;

    When the exact type is the point, auto is the wrong tool and a vague type is no better: std::int64_t says the width in the declaration itself.

Practise: predict ten types

For each declaration in the file, replace void with the type that auto or decltype deduces on that line. The static_assert lines check every answer while the file compiles, so the exercise is solved when it builds. Write your answers first; a failing check then shows the real type, so you can learn from each one.

predict_types.cpp C++
// Exercise: replace each void with the type that auto or decltype deduces on the same line.
// The static_asserts at the end check every answer: it is solved when the file builds.
#include <string>
#include <type_traits>
#include <vector>

int main() {
    const int limit = 10;
    int count = 3;
    int& ref = count;
    const std::string name = "Meera";
    std::vector<int> v{1, 2, 3};
    std::vector<bool> bits(8);

    auto t1 = limit;               using answer1 = void;
    auto& t2 = limit;              using answer2 = void;
    auto t3 = ref;                 using answer3 = void;
    decltype(ref) t4 = count;      using answer4 = void;
    decltype((count)) t5 = count;  using answer5 = void;
    auto t6 = name.size();         using answer6 = void;
    auto t7 = v[0] * 2.0;          using answer7 = void;
    const auto& t8 = name;         using answer8 = void;
    auto t9 = 'a' + 1;             using answer9 = void;
    auto t10 = bits[0];            using answer10 = void;

    static_assert(std::is_same_v<decltype(t1), answer1>, "t1");
    static_assert(std::is_same_v<decltype(t2), answer2>, "t2");
    static_assert(std::is_same_v<decltype(t3), answer3>, "t3");
    static_assert(std::is_same_v<decltype(t4), answer4>, "t4");
    static_assert(std::is_same_v<decltype(t5), answer5>, "t5");
    static_assert(std::is_same_v<decltype(t6), answer6>, "t6");
    static_assert(std::is_same_v<decltype(t7), answer7>, "t7");
    static_assert(std::is_same_v<decltype(t8), answer8>, "t8");
    static_assert(std::is_same_v<decltype(t9), answer9>, "t9");
    static_assert(std::is_same_v<decltype(t10), answer10>, "t10");
    (void)t1; (void)t2; (void)t3; (void)t4; (void)t5; (void)t6; (void)t7; (void)t8; (void)t9; (void)t10;
}

As given, all ten checks fail. The session counts them without showing the compiler’s messages, which contain the answers:

Failing checks in the exercise as given Python · predict_types_session.py
from session import run

run("""
# How many of the ten checks fail? grep -c counts the lines of the compiler's output that report one.
clang++ -std=c++23 -fsyntax-only predict_types.cpp 2>&1 | grep -c 'static assertion failed'
g++-16 -std=c++23 -fsyntax-only predict_types.cpp 2>&1 | grep -c 'static assertion failed'
""")

Output

# How many of the ten checks fail? grep -c counts the lines of the compiler's output that report one.
$ clang++ -std=c++23 -fsyntax-only predict_types.cpp 2>&1 | grep -c 'static assertion failed'
10
$ g++-16 -std=c++23 -fsyntax-only predict_types.cpp 2>&1 | grep -c 'static assertion failed'
10

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 predict_types_session.py

First hint: start from the three rules of auto (references dropped, top-level const dropped, arrays and functions become pointers), remember that decltype keeps references, and that 'a' + 1 is computed in the type that char is integral promotion: The conversion of an operand narrower than int, such as bool, char, unsigned char or short, to int before arithmetic, so that 200 + 100 with unsigned char operands is the int 300. More in “Integer overflow and signed/unsigned conversions” to.

Once the file builds, test yourself on all seven ideas. The questions start with the idea you have answered least well so far, and each option you pick tells you what it gets right or misses:

Practice that adapts to you

Practise this lesson

18 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 18 What type does auto j = {5}; give j?

    Choose one answer.

    Show the answer: Question 1 of 18

    Answer: std::initializer_list<int>

    With = and braces, auto deduces a std::initializer_list. Without the =, auto j{5}; deduces int (since C++17).

  2. Question 2 of 18 What happens on the last line?

    Read the code, then choose one answer.

    const std::vector<int> totals{4, 5};
    auto t = totals;
    t.push_back(6);
    Show the answer: Question 2 of 18

    Answer: It compiles: t is a std::vector<int> copy, now with 3 elements, and totals still has 2

    auto copies the value: the whole vector is copied into t, without the const, so push_back works on the copy and totals keeps its 2 elements.

  3. Question 3 of 18 longest returns a reference to the longest string in the vector it is given. What happens to names?

    Read the code, then choose one answer.

    const std::string& longest(const std::vector<std::string>& v);
    
    auto s = longest(names);
    s += "!";
    Show the answer: Question 3 of 18

    Answer: Nothing: s is a std::string copy, so only the copy ends with !

    The rules do not care where the initializer comes from: a function call that returns const std::string& is deduced exactly like a const reference variable, so s is a new std::string.

  4. Question 4 of 18 What does v hold after this loop?

    Read the code, then choose one answer.

    std::vector<int> v{1, 2, 3};
    for (auto x : v) x = 0;
    Show the answer: Question 4 of 18

    Answer: [1, 2, 3]

    Each x is a copy of an element, so setting it to 0 changes only the copy. Both compilers warn that x is set but never used. for (auto& x : v) would set the elements to 0.

  5. Question 5 of 18 What are the types of a and b?

    Read the code, then choose one answer.

    const std::string name = "Asha";
    auto a = name;
    auto& b = name;
    Show the answer: Question 5 of 18

    Answer: a is std::string, b is const std::string&

    auto drops the top-level const, so a is a modifiable copy. With auto& nothing is dropped, and the reference must keep the const of the object it refers to.

  6. Question 6 of 18 cities is a const std::vector<std::string>. Which of these loops copy no string?

    Choose every answer that is right.

    Show the answer: Question 6 of 18

    Answer:

    • for (const auto& c : cities)
    • for (auto& c : cities)

    With a const vector, auto& and const auto& deduce the same type, const std::string&, because auto& keeps the const of the object it refers to. Writing const auto& still says the intent more plainly.

  7. Question 7 of 18 Why is decltype(v[0]) an int& for a std::vector<int> v?

    Choose one answer.

    Show the answer: Question 7 of 18

    Answer: v[0] calls operator[], which returns int&, and decltype gives the type that call returns

    decltype names the type of an expression without evaluating it: for v[0] that is the return type of operator[], int&.

  8. Question 8 of 18 int x = 0; and std::vector<int> v{1, 2, 3}; are declared. Which of these name the type int&?

    Choose every answer that is right.

    Show the answer: Question 8 of 18

    Answer:

    • decltype(v[0])
    • decltype((x))

    decltype(x) is the declared type, int, and x + 1 is a computed value of type int. Extra parentheses make (x) an expression that refers to an object, so decltype((x)) is int&, and v[0] calls operator[], which returns int&.

  9. Question 9 of 18 A function template must return exactly what c[i] returns for any container c, a reference when that is one. Which return type does that?

    Choose one answer.

    Show the answer: Question 9 of 18

    Answer: decltype(auto)

    decltype(auto) is mostly used for return types that must keep a reference: whatever c[i] is, the function returns exactly that type.

  10. Question 10 of 18 std::vector<bool> flags(4); Which declaration gives a plain bool, unaffected by later changes to the vector?

    Choose one answer.

    Show the answer: Question 10 of 18

    Answer: bool b = flags[2];

    Only a declaration that names bool turns the proxy into a value; every form of auto keeps the type the initializer has.

  11. Question 11 of 18 auto dangling = make_flags()[0]; compiles without a warning. Why does auto& dangling = make_flags()[0]; not compile at all?

    Choose one answer.

    Show the answer: Question 11 of 18

    Answer: operator[] returns the proxy itself, a new temporary object: auto copies it, but a non-const reference cannot bind to a temporary

    flags[i] on a std::vector<bool> makes a new proxy each time and returns it by value. auto copies that proxy, which compiles and still points into the vector; auto& refuses, because a non-const reference cannot bind to a temporary.

  12. Question 12 of 18 What does auto n = std::vector<int>(5).size(); deduce?

    Choose one answer.

    Show the answer: Question 12 of 18

    Answer: std::size_t, an unsigned type

    std::size_t is unsigned and 8 bytes here. auto keeps it, and an int compared with it is converted to the unsigned type, which is why both compilers warned.

  13. Question 13 of 18 The same line, auto big = 3'000'000'000;, is built on 64-bit Windows. What does it deduce there?

    Choose one answer.

    Show the answer: Question 13 of 18

    Answer: long long, because long has only 4 bytes on Windows

    Microsoft documents long as 4 bytes on Windows, so the literal there is a long long. The source is the same, but the deduced type is not, which is why the type is written out when it matters.

  14. Question 14 of 18 With using Metres = double; and using Seconds = double;, what happens to Metres m = Seconds{3.0};?

    Choose one answer.

    Show the answer: Question 14 of 18

    Answer: It compiles: both aliases name the same type, double

    An alias is another name for an existing type, not a new type, so the compiler sees double m = double{3.0};. To make such mistakes errors, give each unit a type of its own.

  15. Question 15 of 18 What does the last line do?

    Read the code, then choose one answer.

    using Dist = double;
    using Weight = double;
    double cost(Dist d, Weight w);
    
    cost(Weight{2.0}, Dist{3.0});
    Show the answer: Question 15 of 18

    Answer: It compiles and silently passes the weight as the distance

    Aliases document intent for readers only. The swapped call compiles exactly as Metres plus Seconds did.

  16. Question 16 of 18 You want passing a time where a distance is expected to be a compile error. What do you change?

    Choose one answer.

    Show the answer: Question 16 of 18

    Answer: Give each its own type, for example struct Metres { double value; }; and struct Seconds { double value; };

    Only a new type can be checked by the compiler: small structs (a later module) or an enum class for a set of named values.

  17. Question 17 of 18 What is the usual way to loop over a vector of strings that you only read?

    Choose one answer.

    Show the answer: Question 17 of 18

    Answer: for (const auto& s : words)

    const auto& is the reading loop: no copy, and the compiler stops an accidental change.

  18. Question 18 of 18 Which declaration is the best place for auto?

    Choose one answer.

    Show the answer: Question 18 of 18

    Answer: auto p = std::make_unique<Order>();

    Use auto where the type is visible in the initializer, long, or impossible to write; write the type where the type is the point.

Interview questions

Fresher · What does auto deduce for auto x = r; when r is a const int&?

It deduces int. auto deduces the type of the value, so it drops the reference and then the top-level const, and x is a separate, modifiable copy. To keep the reference write auto& x = r;, which deduces const int& because the const now belongs to the object referred to; const auto& x = r; says the same thing more explicitly. decltype(r) x = r; would also give const int&.

An interviewer who hears that answer often changes one character of the declaration and asks again. Pick an answer to each of these two follow-ups, and read why each option holds or fails:

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 Follow-up: "With const int& r = limit;, what does auto p = &r; deduce?"

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: const int*: the const belongs to the int that p points at, so it is not top-level and stays

    The strong answer applies the same two rules again: no reference to drop, because &r is a pointer, and no top-level const, because the const describes the pointed-to int.

  2. Question 2 of 2 Follow-up: "With const int limit = 10; and const int& r = limit;, what do decltype(auto) y = r; and decltype(auto) z = (limit); deduce?"

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Both are const int&

    decltype(auto) is decltype applied to the initializer: a plain name gives what it was declared as, and a parenthesised name gives an lvalue reference. That is why decltype(auto) can return a dangling reference when a return statement wraps a local in parentheses.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    The loop for (auto order : orders) order.status = Status::shipped; compiles, but no order is ever marked as shipped, and a profile shows the loop spending most of its time copying. Explain both symptoms and the fix.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    A function returns std::vector<bool>, and a caller writes auto ok = check_all()[0]; and uses ok a few lines later. It seems to work in tests, but AddressSanitizer reports a heap-use-after-free. Explain why, and how to make such code safe.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • auto deduces the type of the initializer’s value: references and top-level const are dropped, arrays become pointers.
  • auto& and const auto& keep the original object, for elements you change or only read; auto&& binds to anything and is mostly for generic code.
  • decltype(x) is the declared type, decltype((x)) an lvalue reference, and decltype(auto) deduces with decltype rules.
  • auto keeps proxy types (std::vector<bool>::reference) and literal types (long or long long): write the type when it matters.
  • using Name = Type; makes an alias, also for templates; an alias is not a new type.
  • Choose by what the code needs: auto where the type is plain to see or cannot be written, a reference for the original object, and the written type when the type is the point.

Terms in this lesson

alias template
A type alias with template parameters, such as template <typename T> using Grid = std::vector<std::vector<T>>;, which typedef cannot write.
array-to-pointer conversion
The implicit conversion of an array to a pointer to its first element, which happens in most uses of an array, such as auto f = scores;. The pointer no longer carries the array's length.
forwarding reference
A reference written auto&&, or T&& in a template whose T is deduced, that binds to anything: it becomes an lvalue reference for a named variable and an rvalue reference for a temporary.
lvalue
An expression that refers to an object with an identity, such as a named variable, (x) or v[0]. decltype gives a reference type, such as int&, for an lvalue that is not a plain name.
proxy object
An object returned in place of a reference, standing for an element that cannot be referred to directly, as std::vector<bool>::reference stands for one bit. It points into its container and is valid only while the container lives.
top-level const
A const that applies to an object itself, as in const int or int* const, rather than to what a pointer or a reference leads to. auto drops it, because the new variable is a separate object.
type alias
A second name for an existing type, made with using Name = Type; or typedef. It makes no new type, so values of the alias and of the original type mix freely.
type deduction
The compiler working out a type from an initializer or an argument instead of reading it from the declaration, as it does for auto, decltype(auto) and the parameters of function templates.

Corrections

  • The opening now says that some deductions, such as those of the loops and of auto&&, are shown by what the programs print rather than by a static_assert.

References

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.