Skip to content
Learn Netverks

Lesson

Step 24/36 67% through track

smart-pointers

Smart pointers

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Smart pointers: the syntax, patterns, and safety habits you need before advancing in C++.

Modern C++ prefers unique_ptr and move semantics over raw new/delete—teams expect this in new code.

You will apply Smart pointers in contexts like: Modern services and engines migrating off raw pointers to safer ownership.

Write C++ in main.cpp with int main(), click Run on server—the dev runner compiles with c++/g++ -std=c++17 -Wall and runs the binary; read template errors in stderr (LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Smart pointers wrap raw pointers with RAII ownership—automatically calling delete when the last owner goes away. Prefer them over scattered new/delete.

std::unique_ptr

auto p = std::make_unique<int>(42);
// delete called when p goes out of scope

unique_ptr has exclusive ownership—it is move-only, not copyable.

std::shared_ptr (preview)

shared_ptr uses reference counting when multiple owners must share one object. Default to unique_ptr; reach for shared_ptr when sharing is required.

Important interview questions and answers

  1. Q: make_unique benefits?
    A: Exception-safe, concise, avoids writing new directly.
  2. Q: unique_ptr vs shared_ptr?
    A: Exclusive vs shared ownership; shared_ptr has atomic refcount overhead.

Self-check

  1. Can you copy a unique_ptr?
  2. When is delete called for unique_ptr?

Tip: Default to std::unique_ptr for exclusive ownership—like Rust move ownership, but enforced by convention and move-only types.

Interview prep

unique_ptr vs shared_ptr?

unique_ptr has exclusive ownership; shared_ptr uses reference counting for shared ownership.

make_unique benefits?

Exception-safe creation without writing new directly in user code.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • unique vs shared?
  • make_unique why?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump