Cambo Freelance
ទំព័រដើមសេវាកម្មអត្ថបទការបង្រៀនក្រុមវគ្គបណ្តុះបណ្តាលទំនាក់ទំនង
Cambo Freelance

Professional freelance team from Cambodia delivering technology-driven solutions with cultural insight and modern expertise.

ផ្ញើសាររបស់អ្នក

ត្រៀមចាប់ផ្តើមគម្រោងរបស់អ្នក? ទំនាក់ទំនងក្រុមរបស់យើង។

ទំនាក់ទំនង

សេវាកម្ម

  • Web & Mobile Development Services
  • Graphic Design & Branding Services

តំណភ្ជាប់មានប្រយោជន៍

  • ទំព័រដើម
  • សេវាកម្ម
  • ការសិក្សា
  • អំពីយើង
  • ទំនាក់ទំនង
  • តម្លៃ

© 2026 Cambo Freelance. រក្សាសិទ្ធិទាំងអស់។

TelegramFacebookLinkedInEmail
HomeTutorialsC++C++ Smart Pointers
⚡C++ Tutorials

50 lessons

Beginner(21)1C++ Introduction2C++ Getting Started3C++ Syntax4C++ Output5C++ Comments6C++ Variables7C++ Data Types8C++ Constants9C++ User Input10C++ Operators11C++ Strings12C++ Math13C++ Booleans14C++ Conditions15C++ Switch16C++ Loops17C++ Break and Continue18C++ Arrays19C++ Functions20C++ References21C++ Pointers
Intermediate(19)22C++ Classes23C++ Objects24C++ Constructors25C++ Access Specifiers
Advanced(10)41C++ Smart Pointers42C++ Templates43C++ Lambda Functions44
⚡

C++ Tutorials

Lesson 41 of 50

All lessons
Beginner (21)1C++ Introduction2C++ Getting Started
26
C++ Encapsulation
27C++ Inheritance
28C++ Polymorphism
29C++ Abstraction
30C++ Files
31C++ Exception Handling
32C++ Namespaces
33C++ Structures
34C++ Enumerations
35C++ STL Introduction
36C++ Vectors
37C++ Maps
38C++ Sets
39C++ Queues
40C++ Stacks
C++ Move Semantics
45C++ Multithreading
46C++ Design Patterns
47C++ Memory Management
48C++17 Features
49C++20 Features
50C++ Performance Optimization
3
C++ Syntax
4C++ Output
5C++ Comments
6C++ Variables
7C++ Data Types
8C++ Constants
9C++ User Input
10C++ Operators
11C++ Strings
12C++ Math
13C++ Booleans
14C++ Conditions
15C++ Switch
16C++ Loops
17C++ Break and Continue
18C++ Arrays
19C++ Functions
20C++ References
21C++ Pointers
Intermediate (19)22C++ Classes23C++ Objects24C++ Constructors25C++ Access Specifiers26C++ Encapsulation27C++ Inheritance28C++ Polymorphism29C++ Abstraction30C++ Files31C++ Exception Handling32C++ Namespaces33C++ Structures34C++ Enumerations35C++ STL Introduction36C++ Vectors37C++ Maps38C++ Sets39C++ Queues40C++ Stacks
Advanced (10)41C++ Smart Pointers42C++ Templates43C++ Lambda Functions44C++ Move Semantics45C++ Multithreading46C++ Design Patterns47C++ Memory Management48C++17 Features49C++20 Features50C++ Performance Optimization
⚡C++AdvancedLesson 41 of 50CamboFreelanceJune 19, 2026

C++ Smart Pointers

Master C++ smart pointers: unique_ptr for exclusive ownership, shared_ptr for shared ownership, and weak_ptr to break cycles.


Tutorials › C++ › Smart Pointers
Advanced10 min readLesson 41 of 50

Why Smart Pointers?

Raw pointers require manual new/delete, risking memory leaks. Smart pointers (C++11, <memory>) manage memory automatically using RAII.

unique_ptr — Exclusive Ownership

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

struct Resource {
    string name;
    Resource(string n) : name(n) { cout << name << " created\n"; }
    ~Resource()                  { cout << name << " destroyed\n"; }
};

int main() {
    {
        unique_ptr<Resource> p1 = make_unique<Resource>("DB Connection");
        cout << "Using: " << p1->name << endl;
    }   // p1 goes out of scope — automatically destroyed
    cout << "After scope" << endl;
    return 0;
}

Output:

DB Connection created
Using: DB Connection
DB Connection destroyed
After scope

shared_ptr — Shared Ownership

Multiple shared_ptrs can own the same resource. It is destroyed when the last owner goes out of scope (reference counting).

shared_ptr<Resource> p1 = make_shared<Resource>("Config");
{
    shared_ptr<Resource> p2 = p1;   // shared ownership
    cout << "Use count: " << p1.use_count() << endl;  // 2
}   // p2 destroyed, use_count drops to 1
cout << "Use count: " << p1.use_count() << endl;      // 1
// When p1 goes out of scope, Resource is finally destroyed

weak_ptr — Non-Owning Observer

weak_ptr observes a shared_ptr without extending its lifetime — breaks circular references:

shared_ptr<int> sp = make_shared<int>(42);
weak_ptr<int> wp = sp;

if (auto locked = wp.lock()) {   // check if still alive
    cout << *locked << endl;     // 42
}
Rule: Prefer unique_ptr by default. Use shared_ptr when ownership is genuinely shared. Use weak_ptr to break circular shared_ptr cycles.

Exercise

Create a FileLogger class. Use unique_ptr to manage it in main. Transfer ownership to a function process(unique_ptr<FileLogger>) using std::move.

Show Solution
#include <iostream>
#include <memory>
using namespace std;

class FileLogger {
  public:
    FileLogger()  { cout << "Logger opened\n"; }
    ~FileLogger() { cout << "Logger closed\n"; }
    void log(const string& msg) { cout << "[LOG] " << msg << endl; }
};

void process(unique_ptr<FileLogger> logger) {
    logger->log("Processing...");
}   // logger destroyed here

int main() {
    auto logger = make_unique<FileLogger>();
    logger->log("Starting");
    process(move(logger));   // transfer ownership
    // logger is now null
    return 0;
}

Quiz

  1. Which smart pointer allows only one owner?

    • A) shared_ptr
    • B) weak_ptr
    • C) unique_ptr
    • D) auto_ptr
    Answer

    C) unique_ptr

  2. What does weak_ptr prevent?

    • A) Memory allocation
    • B) Circular references that prevent destruction
    • C) Multiple ownership
    • D) Stack overflow
    Answer

    B) weak_ptr breaks circular shared_ptr cycles that would cause memory leaks.

Summary

  • unique_ptr — single owner, zero overhead, use move() to transfer.
  • shared_ptr — reference-counted shared ownership.
  • weak_ptr — non-owning observer, breaks cycles.
  • Always use make_unique and make_shared — never use raw new.
← Previous: Stacks Next: Templates →
c++smart-pointersmemoryadvanced
PreviousLesson 40: C++ StacksNextLesson 42: C++ Templates
Back to All Tutorials