Dayrvia
C++

C++

Learn vectors and references, then trace const references and smart-pointer ownership.

Take the full quiz

ContainersVectors

Growing a vector

A std::vector holds a variable number of elements. push_back adds one at the end and size returns the current count.

Code example

std::vector<int> v{2, 5};
v.push_back(8);

Walkthrough

Appending 8 makes it the third element. The size becomes 3 and the first value stays 2.

ReferencesCopies and references

A copy or another name?

int b = a creates a separate integer. int& r = a binds a reference to the existing one. Mark which names refer to the same object.

Code example

int a = 2;
int b = a;
int& r = a;
r = 7;

Walkthrough

Writing through r changes a to 7. The independent copy b stays 2.

ContainersRange-based loops

Modifying elements in a range loop

A range loop can copy each element or bind to it. Use a reference type for the loop variable when you intend to modify the element.

Code example

std::vector<int> v{2, 3};
for (int& x : v) x *= 2;

Walkthrough

Each x refers to an element, so v becomes {4, 6}. With int x, only temporary copies would change.

ReferencesConst references

Read-only reference parameters

Use a const reference to read a container without copying it. The function cannot modify elements through that reference. at checks bounds, so consider how to handle an empty vector.

Code example

int first(const std::vector<int>& v) {
    return v.at(0);
}
std::vector<int> nums{8, 13};
int x = first(nums);

Walkthrough

The vector here is nonempty and x becomes 8. The parameter v refers to nums without copying its elements.

MemoryOwnership

Moving unique ownership

std::unique_ptr represents one owner of a resource. Move construction or assignment transfers ownership. When the owner goes out of scope, the resource is released automatically.

Code example

auto a = std::make_unique<int>(5);
auto b = std::move(a);
*b = 7;

Walkthrough

After the move, a is empty and b owns the integer. Assigning through b stores 7. Include <memory> for make_unique and <utility> for move.

Further reading