C++ CPP study materials
C++ CPP study resources

A mutable captured copy and the original variable

C++ CPP · Put your knowledge to work in context.

All case studies

A mutable captured copy and the original variable

A fictional program initializes an integer counter and creates a lambda capturing that counter by value. The lambda is mutable and increments its captured value each time it is called. The study record distinguishes the enclosing variable from the closure object, and repeated calls use the same closure instance. A colleague says mutable makes the capture an alias for the original counter and therefore every call must change the enclosing variable. Another traces the objects and their lifetimes before choosing an output. This written case changes no production code. It asks how value capture differs from reference capture and why copying the closure itself would introduce a separate state history.

1. Which object changes in the supplied lambda?

Read the worked answer

The mutable lambda changes its captured copy stored in that closure object. Capturing by value does not turn the original variable into an alias.

2. What would copying the closure change?

Read the worked answer

The copy has its own copied capture state, subject to the captured object’s semantics. Its later mutation need not advance the state of the original closure or enclosing variable.