🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C++ Smart Pointers — Complete Beginner Guide

C++ FundamentalsC++ Smart Pointers — unique_ptr, shared_ptr, weak_ptr🟢 Free Lesson

C++ Smart Pointers — Complete Beginner Guide

Learning Objectives

  • Create exclusive ownership with unique_ptr
  • Share ownership with shared_ptr
  • Break cycles with weak_ptr
  • Decide which smart pointer fits your design

Why Smart Pointers Exist

Raw pointers do not clean up after themselves when they go out of scope. If you forget delete, memory leaks. If you delete twice, the program may crash. Smart pointers wrap a raw pointer and run cleanup automatically when the wrapper ends its life.

unique_ptr for Exclusive Ownership

unique_ptr represents the single owner of an object. Copying is forbidden; moves transfer ownership.

#include <iostream>
#include <memory>

int main() {
    std::unique_ptr<int> p = std::make_unique<int>(42);
    std::cout << *p << std::endl;
    return 0;
} // p releases the integer automatically here
PropertyBehavior
OwnershipExactly one owner
CopyNot allowed
MoveAllowed and common
CostVery lightweight

When the unique_ptr leaves scope, the managed object is destroyed. You rarely write delete for application data.

Transferring Ownership

std::unique_ptr<int> a = std::make_unique<int>(7);
std::unique_ptr<int> b = std::move(a);

// a no longer owns the value
// b is now the owner

Moving makes the transfer explicit and safe.

shared_ptr for Shared Ownership

shared_ptr keeps a reference count so several owners can cooperate. The last owner out destroys the object.

std::shared_ptr<int> a = std::make_shared<int>(10);
std::shared_ptr<int> b = a; // count increases

// both end together; object deletes when count reaches zero
PropertyBehavior
OwnershipShared by many
CopyAllowed and increments count
OverheadControl block and count updates
Best useTruly shared lifetime graphs

Use shared_ptr only when multiple owners are real. Sprinkling shared_ptr everywhere hides design problems and adds cost.

weak_ptr for Non Owning Links

weak_ptr observes an object without owning it. It does not keep the object alive by itself. Use it to break reference cycles and to form parent style links.

std::shared_ptr<int> strong = std::make_shared<int>(5);
std::weak_ptr<int> weak = strong;

if (std::shared_ptr<int> live = weak.lock()) {
    std::cout << *live << std::endl;
} else {
    std::cout << "already gone" << std::endl;
}

The lock method returns a shared_ptr only when the object still exists. If the strong owners are all gone, lock fails and you handle the empty case.

Choosing The Right Type

QuestionGood Answer
One clear owner?unique_ptr
Shared resource across owners?shared_ptr
Temporary look back without ownership?weak_ptr
No dynamic lifetime needed?Stack object instead

make_unique and make_shared

Prefer the factory helpers over raw new.

auto u = std::make_unique<int>(1);
auto s = std::make_shared<int>(2);

They allocate and set up ownership in one step, reduce typing mistakes, and in the shared case set up the control block efficiently.

Smart Pointers and Arrays

unique_ptr has an array form for dynamic arrays. For most code, standard vector is still nicer than manual dynamic arrays because it tracks size and offers methods.

std::unique_ptr<int[]> arr = std::make_unique<int[]>(5);
arr[0] = 1;

Common Mistakes

MistakeBetter Move
shared_ptr everywhere by habitStart with unique_ptr
Storing this as shared_ptr in a memberKeep raw this or weak look backs
Mixing raw delete with smart ownersLet the smart pointer own fully
Cyclic shared_ptr linksInsert weak_ptr on one side
Ignoring null returns from lockCheck before use

Cycles Explained Simply

If object A holds a shared_ptr to B and B holds a shared_ptr back to A, their counts never reach zero. Memory leaks follow. Store one direction as weak_ptr so the strong count can fall to zero and cleanup can happen.

A Small Design Example

#include <iostream>
#include <memory>
#include <string>

class Node {
public:
    std::string name;
    std::shared_ptr<Node> next;

    explicit Node(std::string n) : name(std::move(n)) {}
};

int main() {
    auto head = std::make_shared<Node>("head");
    auto tail = std::make_shared<Node>("tail");
    head->next = tail;

    std::cout << head->name << " -> " << head->next->name << std::endl;
    return 0;
}

Ownership flows forward. A reverse back pointer, if added, should be weak.

Key Takeaways

💡

  • unique_ptr is the default choice for single ownership
  • shared_ptr coordinates shared lifetime with reference counting
  • weak_ptr observes without owning and breaks cycles
  • make_unique and make_shared are preferred constructors
  • Smart pointers shine for dynamic lifetime, not every variable

Practice Questions

  1. Convert a raw new and delete pattern into unique_ptr usage.
  2. When does a shared_ptr delete the managed object?
  3. How does weak_ptr help prevent leaks in linked structures?

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C++ Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement