← SEARCHABLE ARCHIVE
C / C++ · 2026-06-23

C++ from Basics to Mastery — Part 9

Expressing ownership with smart pointers

INTERACTIVE READING MODE →

The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.

Using pointers does not cause problems. The problem arises when raw pointers are used as ownership without knowing who should destroy the object.

Smart pointers express ownership as a type.

unique_ptr

std::unique_ptrhas sole ownership.

#include <memory>

auto warrior = std::make_unique<Warrior>("Rose");
std::cout << warrior->Attack() << '\n';

Without calling new directlystd::make_uniqueCreate an object with If unique_ptr goes out of scope, the owning object is automatically destroyed.

Since it is solely owned, it cannot be copied, but it can be moved.

std::vector<std::unique_ptr<Character>> party;

auto warrior = std::make_unique<Warrior>("Rose");
party.push_back(std::move(warrior));

std::moveAfterwards, warrior becomes empty and ownership moves to vector. std::move itself serves to treat it as a movable value rather than a function for moving objects.

shared_ptr

A single monster may need to be owned by both the active list and the combat system. At this timestd::shared_ptrcan be used.

auto monster = std::make_shared<Monster>(1, "Slime", 30);

std::vector<std::shared_ptr<Monster>> activeMonsters;
std::queue<std::shared_ptr<Monster>> spawnQueue;

spawnQueue.push(monster);
activeMonsters.push_back(monster);

When shared_ptr is copied, the object is not copied, but its reference count is incremented. The actual object is destroyed when its last owner disappears.

It is not a good idea to make all pointers into shared_ptr just because of convenience. Who owns it becomes unclear, circular references may occur, and there are reference count management costs.

weak_ptr

If you do not own an object like the current target and only want to observe it,std::weak_ptrUse .

std::weak_ptr<Monster> currentTarget;

currentTarget = monster;

if (auto target = currentTarget.lock())
{
    std::cout << target->GetHealth() << '\n';
}

weakptr does not extend the lifetime of an object. If the target is alivelock()Returns this sharedptr, or if it has already been destroyed, returns an empty shared_ptr.

To summarize, if there is only one owner, uniqueptr, If multiple systems really need to own sharedptr, If you only view it without owning it, it is weak_ptr.

When ownership is revealed in the code, there is less time to worry about when to delete.