SyntaxPilot
Courses/C++ Coding Questions/Lesson 27
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ Coding Questions · Lesson 27 of 30

Modern C++ questions

lambda capture by reference that outlives its variablemoved-from strings (std::move)range-for copying vs auto&

These are the notes for C++ Coding Questions, episode 27, placement practice for people who finished the SyntaxPilot C++ course. Modern C++ (C++11 and later) gave us lambdas, std::move and the range-for loop. They make code shorter, and each hides a classic bug that interviewers love: a lambda that captures by reference and runs after the variable is gone, a string that is suddenly empty after a move, and a loop that changes a copy instead of the real element.

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the cost.

Every program was compiled with g++ -Wall -O2 -std=c++17 main.cpp -o main (g++ 13.3, Linux x86-64), the SyntaxPilot compiler's C++ command with warnings on, and every output below is real, including the compiler errors.

Real-life pictures

In real life In C++
A fridge note: "pay what's on the whiteboard" a lambda capturing by reference ([&])
The board is wiped and rewritten: both notes now mean "school fees" the captured variable is gone; its memory is reused
Copying the bill's name onto the note itself capturing by value ([name], [=])
Photocopying a thick patient file copying a string: O(length)
Just handing the file to the receptionist std::move: hands over the contents, O(1)
Your hands are now empty a moved-from object
A teacher writing grace marks on photocopies for (auto s : v): changes a copy
Writing on the original sheet for (auto& s : v)
Reading the original without photocopying it for (const auto& s : v)

Q1: Lambda captures

Problem. addReminder(name) stores a job in a global vector, to run later. main adds "electricity bill" and "school fees", then runs every job. Expected:

Reminder: pay electricity bill
Reminder: pay school fees

Think out loud. A lambda is a small function written right where you need it: [capture](parameters) { body }. The capture list in square brackets says how the lambda may use variables from the code around it:

Capture Meaning
[] uses no outside variables
[&] uses every outside variable it mentions by reference (the variable itself)
[=] keeps a copy of every outside variable it mentions
[name] keeps a copy of name only
[&name] refers to name only
[n = expr] a copy under a new name (C++14)

A std::function<void()> can hold any callable with that signature, so a vector<function<void()>> can hold many lambdas.

By reference, run right away: fine

#include <iostream>
#include <string>
using namespace std;

int main() {
    string bill = "electricity bill";
    auto remind = [&]() { cout << "Reminder: pay " << bill << "\n"; };
    remind();                            // runs now: bill is alive
    bill = "school fees";
    remind();                            // [&] sees the NEW value
    return 0;
}

Output:

Reminder: pay electricity bill
Reminder: pay school fees

[&] sees the live variable, so the second call sees the new value. That is fine because bill is still alive whenever remind() runs.

The obvious attempt: by reference, run later

#include <iostream>
#include <string>
#include <vector>
#include <functional>
using namespace std;

vector<function<void()>> reminders;      // jobs to run later

void addReminder(string name) {
    reminders.push_back([&]() {          // capture by reference
        cout << "Reminder: pay " << name << endl;
    });
}

int main() {
    addReminder("electricity bill");
    addReminder("school fees");
    cout << "running reminders..." << endl;
    for (auto& r : reminders) r();
    return 0;
}

Output (no error, no warning):

running reminders...
Reminder: pay school fees
Reminder: pay school fees

Why

name is a parameter of addReminder: a local variable that is destroyed when the function returns. [&] stored only a reference to it, but the lambda lives on in the global vector and runs later, after both calls have returned. Both references dangle (exactly like returning a reference to a local in episode 26). Using them is undefined behaviour. Here, the second call to addReminder happened to put its name in the same stack memory as the first, so both lambdas read "school fees". It could just as well print garbage or crash; g++ gives no warning for this.

The fix: capture by value

    reminders.push_back([name]() {       // capture a COPY of name

Output:

running reminders...
Reminder: pay electricity bill
Reminder: pay school fees

Each lambda now carries its own copy of name, so it no longer depends on the function that created it.

Rule. If a lambda may run after the current function returns (stored in a container, returned, given to a thread or a callback), capture by value. Use [&] only for lambdas that run while everything they refer to is alive (e.g. a comparator passed to sort).

Cost. Capturing a string by value copies it: O(L) time and space per lambda, for a name of length L.

Q2: What std::move leaves behind

Problem. Put patient names into a vector<string> queue without copying the strings.

Think out loud. Copying a string duplicates every character: O(length). For big strings that is slow:

#include <iostream>
#include <string>
#include <vector>
#include <chrono>
#include <utility>
using namespace std;
using namespace std::chrono;

int main() {
    string report(1000000, 'x');         // one big 1 MB report
    vector<string> a, b;
    auto t0 = steady_clock::now();
    for (int i = 0; i < 100; i++) a.push_back(report);   // 100 copies
    auto t1 = steady_clock::now();
    for (auto& r : a) b.push_back(move(r));              // 100 moves
    auto t2 = steady_clock::now();
    cout << "100 copies: " << duration_cast<microseconds>(t1 - t0).count() << " us\n";
    cout << "100 moves:  " << duration_cast<microseconds>(t2 - t1).count() << " us\n";
    return 0;
}

One real run (the numbers change from run to run and machine to machine; the gap does not):

100 copies: 43503 us
100 moves:  6 us

A move hands over the string's internal buffer (a pointer, a length and a capacity) instead of copying the characters: O(1).

Here is the surprise: std::move(x) does not move anything by itself. It is only a cast: it marks x as "you may take its contents" (it turns x into an rvalue). The function that receives it, here push_back, then chooses its moving version and steals the contents.

The obvious attempt: keep using the string

#include <iostream>
#include <string>
#include <vector>
#include <utility>
using namespace std;

int main() {
    vector<string> queue;
    string patient = "Priya";
    queue.push_back(move(patient));      // move: no copy
    cout << "in the queue: " << queue[0] << "\n";
    cout << "calling: [" << patient << "]\n";
    cout << "length: " << patient.size() << "\n";
    return 0;
}

Output:

in the queue: Priya
calling: []
length: 0

Why

The contents were handed over to queue[0]. The C++ standard says a moved-from standard object is in a valid but unspecified state: it is still a working string (you can assign to it, call size(), destroy it), but you must not rely on its value. With g++'s library it is empty; another library may leave something else.

The fix: give it a new value before you use it

#include <iostream>
#include <string>
#include <vector>
#include <utility>
using namespace std;

int main() {
    vector<string> queue;
    string patient = "Priya";
    queue.push_back(move(patient));      // patient is now "moved-from"
    patient = "Rahul";                   // give it a new value first
    queue.push_back(move(patient));
    for (const string& p : queue) cout << "in the queue: " << p << "\n";
    const string doctor = "Dr. Mehta";
    string copy = move(doctor);          // const: this silently COPIES
    cout << "doctor: " << doctor << ", copy: " << copy << "\n";
    return 0;
}

Output:

in the queue: Priya
in the queue: Rahul
doctor: Dr. Mehta, copy: Dr. Mehta

Two things to notice:

  • After a move, the safe operations are: assign a new value, or let the object die. Then it is as good as new.
  • move on a const object copies. Stealing would change the object, which const forbids, so the copy constructor is chosen instead. No error, no warning: just a silent, slow copy. Don't declare things const if you plan to move from them.

Exceptions to "unspecified": a moved-from unique_ptr is guaranteed empty (episode 26), and a moved-from vector is in practice empty with g++, but the standard rules are the same: don't read it before assigning.

Cost. Moving a string: O(1). Copying: O(length).

Q3: Range-for copies

Problem. A vector<Student>: Asha 72, Ravi 58, Neha 91. Add 5 grace marks to everyone. Expected: 77, 63, 96.

Think out loud. The range-for loop for (element : container) visits every element, with no index and no off-by-one errors. The question is what the loop variable is: the element itself, or a copy of it?

The obvious attempt

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Student {
    string name;
    int marks;
};

int main() {
    vector<Student> cls = {{"Asha", 72}, {"Ravi", 58}, {"Neha", 91}};
    for (auto s : cls) s.marks += 5;     // grace marks for everyone
    for (auto s : cls) cout << s.name << " " << s.marks << "\n";
    return 0;
}

Output (no error, no warning):

Asha 72
Ravi 58
Neha 91

Why

auto s declares a new variable initialised from each element: a copy. s.marks += 5 changes the copy, which is destroyed at the end of each step. Copying is also slow for big objects: each copy duplicates the name string.

Loop s is Changes stick? Copies?
for (auto s : cls) a copy no one per element
for (auto& s : cls) the real element yes none
for (const auto& s : cls) the real element, read-only not allowed none

Rule. To change elements: auto&. To only read them: const auto&. For small cheap types (int, char, double), plain auto is fine for reading.

The fix, with a copy counter

A copy constructor is the function that makes a copy (Student(const Student& o)). Counting its calls makes copies visible:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Student {
    string name;
    int marks;
    Student(string n, int m) : name(n), marks(m) {}
    Student(const Student& o) : name(o.name), marks(o.marks) { copies++; }
    static int copies;                   // counts every copy
};
int Student::copies = 0;

int main() {
    vector<Student> cls = {{"Asha", 72}, {"Ravi", 58}, {"Neha", 91}};
    Student::copies = 0;
    for (auto& s : cls) s.marks += 5;    // & = the real student
    for (const auto& s : cls) cout << s.name << " " << s.marks << "\n";
    cout << "copies: " << Student::copies << "\n";
    for (auto s : cls) { (void)s; }      // a loop that copies
    cout << "copies after auto s: " << Student::copies << "\n";
    return 0;
}

Output:

Asha 77
Ravi 63
Neha 96
copies: 0
copies after auto s: 3

(Student::copies = 0; resets the counter after building the vector, because initialising a vector from {...} copies each element once. (void)s; just tells the compiler we use s on purpose.)

The special case: vector<bool>

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<bool> present = {true, false, true};   // attendance
    for (auto& p : present) p = true;    // mark everyone present
    for (bool p : present) cout << p << " ";
    cout << "\n";
    return 0;
}

Compiler output:

main.cpp: In function 'int main()':
main.cpp:7:20: error: cannot bind non-const lvalue reference of type 'std::_Bit_reference&' to an rvalue of type 'std::_Bit_iterator::reference'
    7 |     for (auto& p : present) p = true;    // mark everyone present
      |                    ^~~~~~~

vector<bool> is special: it packs 8 values into each byte, so there is no real bool inside to refer to. It hands out a temporary proxy object (std::_Bit_reference) that acts like a bool&, and a plain auto& cannot bind to a temporary. Fix: auto&&, a forwarding reference that binds to anything:

    for (auto&& p : present) p = true;   // auto&&: binds to anything

Output:

1 1 1 

Cost. Each loop is O(n) time. With references the extra space is O(1); with auto it is a full copy of each element, one at a time.

Cost summary

Program Result Cost
[&] lambda run immediately sees the live value O(1) capture
[&] lambda stored and run later both say "school fees" (UB)
[name] lambda each keeps its own copy O(L) per capture
100 copies vs 100 moves of 1 MB tens of ms vs a few µs copy O(L), move O(1)
use a string after move empty here (unspecified)
move of a const string silently copied O(L)
for (auto s : cls) s.marks += 5 unchanged; 3 copies O(n) + copies
for (auto& s : cls) 77, 63, 96; 0 copies O(n), O(1) extra
auto& over vector<bool> compile error use auto&&

Common mistakes (and the real results)

Mistake What you see Why Fix
[&] in a lambda that runs later no error: both reminders say "school fees" the captured variable died [name] or [=]
[&] counter returned from a function garbage like 326423264332644 count died [count]() mutable
changing a by-value capture error: increment of read-only variable 'count' captures are const by default mutable
using a string after move(s) no error: empty here (unspecified) its contents were handed over assign a new value first
move of a const object no error: a silent copy const cannot be stolen from don't make it const
for (auto s : v) s.x += 5; no error: nothing changes s is a copy auto&
for (auto s : v) over big objects correct but slow a copy per element const auto&
auto& over vector<bool> error: cannot bind non-const lvalue reference of type 'std::_Bit_reference&' bits, not bools auto&&, or vector<char>

Mini project: a chai stall order board

Read orders (item and quantity), move each item name into the board (then give the moved-from string a known value), mark small orders ready with auto&, sort with a lambda comparator, print with const auto&, and store a reminder for each unfinished order as a lambda that captures by value ([name = o.item]). The board is cleared before the reminders run, and they still work, because each kept its own copy.

#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <utility>
#include <algorithm>
using namespace std;

struct Order {
    string item;
    int qty;
    bool ready = false;
};

int main() {
    vector<Order> board;
    vector<function<void()>> later;      // jobs to run at closing time
    string item;
    int qty;
    while (cin >> item >> qty) {
        board.push_back({move(item), qty});   // item is moved-from now...
        item.clear();                         // ...so give it a known value
    }
    for (auto& o : board)                     // auto&: change the real orders
        if (o.qty <= 2) o.ready = true;
    sort(board.begin(), board.end(), [](const Order& a, const Order& b) {
        return a.qty > b.qty;                 // biggest orders first
    });
    for (const auto& o : board)               // const auto&: read, no copies
        cout << o.item << " x" << o.qty << (o.ready ? " ready" : " in progress") << "\n";
    for (const auto& o : board)
        if (!o.ready)
            later.push_back([name = o.item]() {   // a copy, under a new name
                cout << "reminder: finish " << name << "\n";
            });
    board.clear();                            // the orders are gone...
    for (auto& job : later) job();            // ...but each job kept its own copy
    return 0;
}

Input:

chai 2
samosa 6
dosa 1
poha 4

Output:

samosa x6 in progress
poha x4 in progress
chai x2 ready
dosa x1 ready
reminder: finish samosa
reminder: finish poha

Try: change [name = o.item] to [&o] and run it. The reminders would refer to orders that board.clear() destroyed: undefined behaviour.

Practice questions (with solutions)

1. Your turn: fix the counter.

function<int()> makeCounter() {
    int count = 0;
    return [&]() { return ++count; };
}
auto next = makeCounter();
cout << next() << next() << next();      // want 123
Solution

count is a local of makeCounter; the returned lambda refers to it after it is destroyed: undefined behaviour. One real run printed 326423264332644.

Capture by value. A by-value capture is read-only by default (error: increment of read-only variable 'count'), so mark the lambda mutable: the lambda's own copy may then change, and it remembers its value between calls.

#include <iostream>
#include <functional>
using namespace std;

function<int()> makeCounter() {
    int count = 0;
    return [count]() mutable { return ++count; };   // its own copy, allowed to change
}

int main() {
    auto next = makeCounter();
    auto other = makeCounter();          // a separate counter
    cout << next() << next() << next() << "\n";
    cout << other() << "\n";
    return 0;
}

Output:

123
1

Each counter has its own count. (Since C++17, the order of evaluation of << operands is left to right, so next() << next() << next() really prints 1, 2, 3 in that order.)

2. Sort a vector<Student> with a lambda comparator. Higher marks first; on a tie, by name. Then count how many scored at least a cutoff.

Solution
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Student { string name; int marks; };

int main() {
    vector<Student> cls = {{"Asha", 72}, {"Ravi", 91}, {"Neha", 91}, {"Aman", 58}};
    sort(cls.begin(), cls.end(), [](const Student& a, const Student& b) {
        if (a.marks != b.marks) return a.marks > b.marks;   // higher marks first
        return a.name < b.name;                             // tie: by name
    });
    for (const auto& s : cls) cout << s.name << " " << s.marks << "\n";
    int cutoff = 70;
    auto passed = count_if(cls.begin(), cls.end(), [cutoff](const Student& s) { return s.marks >= cutoff; });
    cout << passed << " scored " << cutoff << " or more\n";
    return 0;
}

Output:

Neha 91
Ravi 91
Asha 72
Aman 58
3 scored 70 or more

The comparator takes const Student& (no copies) and must be a strict "less than" (episode 11). The count_if lambda captures cutoff by value.

3. Count copies in a range-for over strings.

Solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Name {
    string s;
    static int copies;
    Name(const char* t) : s(t) {}
    Name(const Name& o) : s(o.s) { copies++; }
};
int Name::copies = 0;

int main() {
    vector<Name> names;
    names.reserve(3);
    names.emplace_back("Asha"); names.emplace_back("Ravi"); names.emplace_back("Neha");
    size_t total = 0;
    for (auto n : names) total += n.s.size();          // copies
    cout << "auto:        " << Name::copies << " copies\n";
    Name::copies = 0;
    for (const auto& n : names) total += n.s.size();   // no copies
    cout << "const auto&: " << Name::copies << " copies\n";
    cout << "letters counted: " << total << "\n";
    return 0;
}

Output:

auto:        3 copies
const auto&: 0 copies
letters counted: 24

reserve(3) and emplace_back build the names in place, so the vector itself makes no copies. (24 = 12 letters, counted twice.)

4. Move strings into a vector and time it. Use the copy-vs-move program in Q2. Then try vector<string> b = a; (a copy of the whole vector) against vector<string> b = move(a); (O(1): only three pointers change hands).

Quick quiz

1. What does this print? (the episode quiz)

int x = 1;
auto byVal = [x]()  { return x; };
auto byRef = [&x]() { return x; };
x = 5;
cout << byVal() << byRef();

(A) 11 (B) 15 (C) 51 (D) 55

Answer

(B) 15. [x] copied x when the lambda was created (1). [&x] reads the live x when it runs (5). Real output: 15.

2. After string a = "chai"; string b = move(a);, which is guaranteed: (A) a == "chai" (B) a.empty() (C) a can be assigned to (D) reading a is undefined behaviour

Answer

(C). a is valid but unspecified: you may assign to it, call size(), or destroy it. It is not guaranteed empty (although it is with g++), and reading it is not UB, just unspecified.

3. Does for (const auto& s : v) copy anything? And for (auto s : v) with vector<int>?

Answer

No copies with const auto&. With vector<int>, auto s copies each int, which is as cheap as a reference, so it is fine for reading.

4. Why does [count]() { return ++count; } not compile?

Answer

A lambda's call operator is const by default, so by-value captures are read-only: error: increment of read-only variable 'count'. Add mutable.

5. Is [&] safe in sort(v.begin(), v.end(), [&](int a, int b) { return key[a] < key[b]; });?

Answer

Yes: the lambda runs only inside sort, while key is alive. [&] is dangerous only when the lambda outlives what it refers to.

Interview questions

  1. What is a lambda? An unnamed function object written inline: [capture](params) -> ret { body }. The compiler turns it into a small class with an operator().
  2. Capture by value vs by reference? By value copies the variable when the lambda is created; by reference uses the variable itself when the lambda runs.
  3. When is [&] dangerous? When the lambda runs after a captured variable is destroyed: stored callbacks, returned lambdas, threads.
  4. What does mutable do on a lambda? Lets the lambda change its by-value captures (its own copies).
  5. What is std::function? A type that can hold any callable with a given signature (lambda, function pointer, functor), at a small cost.
  6. What does std::move do? Nothing at run time: it casts its argument to an rvalue, allowing a move constructor or move assignment to be chosen.
  7. What state is a moved-from object in? Valid but unspecified (except types that promise more, like unique_ptr, which is empty). Assign before reading.
  8. Why is moving faster than copying? A move transfers ownership of internal resources (a pointer to the buffer) in O(1); a copy duplicates them.
  9. Why does move on a const object copy? Moving modifies the source; const forbids it, so overload resolution picks the copy constructor.
  10. auto vs auto& vs const auto& in a range-for? A copy; a modifiable reference to the element; a read-only reference.
  11. Why doesn't auto& work with vector<bool>? Its elements are bits; iteration returns temporary proxy objects, which a non-const lvalue reference cannot bind to. Use auto&&.
  12. What is auto&& in a range-for? A forwarding reference: it binds to lvalues and temporaries alike, so it works for any container.

Glossary

Term Meaning Example
Lambda A small unnamed function written inline [](int a) { return a * 2; }
Capture list The [...] part: which outside variables the lambda uses, and how [&], [=], [name]
Capture by reference The lambda uses the variable itself [&], [&x]
Capture by value The lambda keeps its own copy [=], [x]
Init capture A capture with a new name and value (C++14) [name = o.item]
mutable Lets a lambda change its by-value copies [count]() mutable { return ++count; }
std::function A holder for any callable with one signature function<void()>
Callback A function stored now and called later the reminders
Dangling reference Refers to an object that no longer exists [&] after addReminder returns
Undefined behaviour Code the language gives no meaning to both say "school fees"
Copy Duplicating an object's contents: O(size) a.push_back(report)
Move Handing over an object's resources: O(1) b.push_back(move(r))
std::move A cast that says "you may take this object's contents" move(patient)
rvalue A temporary, or something cast with std::move move(x)
Moved-from object An object whose contents were taken patient after the move
Valid but unspecified Still usable (assign, destroy), but its value is unknown calling: []
Range-for loop for (element : container), visits every element for (auto& s : cls)
auto Lets the compiler deduce the type auto s (a copy)
auto& A reference to the real element changes stick
const auto& A read-only reference, no copy printing
auto&& A forwarding reference: binds to anything vector<bool>
Copy constructor Makes a new object as a copy of another Student(const Student& o)
Static data member One variable shared by all objects static int copies;
vector<bool> A space-saving vector that stores bits present
Proxy object A temporary that stands in for an element std::_Bit_reference
Comparator A function that says whether a comes before b the sort lambda

Summary

  • A lambda is [capture](params) { body }. [&] uses the variables themselves, [=] / [name] keep copies.
  • A lambda that runs later (stored, returned, a callback) must capture by value, or it dangles (here both reminders said "school fees").
  • std::move is only a cast: the receiver steals the contents in O(1). A moved-from object is valid but unspecified: assign it a new value before using it. move on a const silently copies.
  • In a range-for, auto copies, auto& changes the real element, const auto& reads it without copying; use auto&& for vector<bool> and other proxies.

Next episode: tricky output questions (the placement round): integer division and casts, signed vs unsigned with v.size() - 1, char arithmetic, i++ + ++i (undefined behaviour), and static locals.