Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 77 ยท C, C++ and Systems Interview Questions

C++: RAII, Smart Pointers and Move Semantics

Prepare C++ interview answers on RAII, the rule of five, unique_ptr and shared_ptr, move versus copy, and virtual functions with a vtable model.

Modern C++ interviews are less about new and delete and more about ownership: who is responsible for each resource, how that responsibility moves, and how the compiler makes cleanup automatic. The recurring questions are "What is RAII?", "What is the rule of five?", "unique_ptr versus shared_ptr?", "What does std::move really do?" and "How do virtual functions work?".

The C++ code in this lesson is read-only (the sandbox cannot compile it inline here), and each idea has a runnable stand-in in JavaScript. JavaScript has a garbage collector, so the stand-ins model the C++ rules by hand (counters, tables, explicit ownership flags); they are teaching models, not C++. The full tutorials are Destructors and RAII, Rule of Zero, Three and Five, unique_ptr, shared_ptr and weak_ptr, Move Semantics and Virtual Functions. The previous lesson is C and C++: Pointers, Memory and Undefined Behavior.

RAII

Q: What is RAII? Resource Acquisition Is Initialization: tie a resource's lifetime to an object's lifetime. The constructor acquires the resource (memory, file, lock, socket), the destructor releases it, and because destructors run when an object leaves scope, even during exceptions, cleanup is automatic and cannot be forgotten.

C++
void log_line(const std::string &text) {
    std::ofstream file("app.log", std::ios::app);   // opened in the constructor
    std::lock_guard<std::mutex> guard(log_mutex);   // locked in the constructor
    file << text << '\n';
}   // guard unlocks, file closes: on return AND on exception

RAII in one picture

Acquire Constructor takes the resource.
Use Object is valid while in scope.
Release Destructor always runs.

Exceptions cannot skip the destructor of a finished object.

1 / 2

The rule of five

Q: What is the rule of three, and the rule of five? If a class manages a resource and you write any one of the special member functions, you almost certainly need to write all of them. Rule of three: destructor, copy constructor, copy assignment. C++11 added move semantics, giving the rule of five: also the move constructor and move assignment operator.

C++
class Buffer {
    std::size_t size_;
    int *data_;
public:
    explicit Buffer(std::size_t n) : size_(n), data_(new int[n]{}) {}
    ~Buffer() { delete[] data_; }                                  // 1 destructor

    Buffer(const Buffer &other)                                    // 2 copy constructor: deep copy
        : size_(other.size_), data_(new int[other.size_]) {
        std::copy(other.data_, other.data_ + size_, data_);
    }
    Buffer &operator=(const Buffer &other) {                       // 3 copy assignment
        if (this != &other) { Buffer tmp(other); swap(tmp); }
        return *this;
    }
    Buffer(Buffer &&other) noexcept                                // 4 move constructor: steal
        : size_(std::exchange(other.size_, 0)), data_(std::exchange(other.data_, nullptr)) {}
    Buffer &operator=(Buffer &&other) noexcept {                   // 5 move assignment
        if (this != &other) { delete[] data_; size_ = std::exchange(other.size_, 0); data_ = std::exchange(other.data_, nullptr); }
        return *this;
    }
    void swap(Buffer &o) noexcept { std::swap(size_, o.size_); std::swap(data_, o.data_); }
};

The better answer is the rule of zero: write none of the five by holding members that already manage themselves (std::vector<int>, std::unique_ptr, std::string), and let the compiler-generated versions do the right thing. Mark move operations noexcept: std::vector only moves elements during reallocation if the move cannot throw; otherwise it copies.

Copy versus move

Q: What is move semantics, and what does std::move do? Copying duplicates a resource; moving transfers it, leaving the source empty but valid. For a buffer, a copy allocates and copies every element; a move just swaps a pointer. std::move itself moves nothing: it is a cast that turns an lvalue into an rvalue reference, which tells overload resolution "you may steal from this". The actual stealing is done by the move constructor or move assignment that gets selected.

After auto b = std::move(a); the object a is in a valid but unspecified state: you may destroy it or assign a new value to it, but you should not rely on its contents. Returning a local by value (return result;) already moves, or the copy is elided entirely, so writing return std::move(result); is a pessimization.

The stand-in counts how many elements are touched when a vector-like buffer is copied versus moved:

JS Stand-in: copy duplicates, move transfers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

unique_ptr and shared_ptr

Q: unique_ptr versus shared_ptr? std::unique_ptr<T> is exclusive ownership: it cannot be copied, only moved, it costs the same as a raw pointer, and it deletes the object when it goes out of scope. std::shared_ptr<T> is shared ownership: copies share a control block holding an atomic reference count, and the object is deleted when the last owner goes away. Prefer unique_ptr by default (and std::make_unique); reach for shared_ptr only when ownership is truly shared.

C++
auto owner = std::make_unique<Widget>();
// auto copy = owner;               // compile error: unique means unique
auto next = std::move(owner);       // ownership transferred; owner is now null

auto a = std::make_shared<Widget>();
auto b = a;                         // same object, use_count() == 2

Q: What is weak_ptr for? A non-owning observer of a shared_ptr object. It does not keep the object alive, and you call lock() to get a temporary shared_ptr (or null if the object is gone). Its main use is breaking reference cycles: two objects holding shared_ptrs to each other would never reach count zero, so one side should use weak_ptr.

Pitfalls: creating two separate shared_ptrs from the same raw pointer (two control blocks, double delete); using shared_ptr as a default "to be safe"; raw new in function arguments in older code.

The stand-in tracks reference counts and shows a cycle that never frees, then the fix with a weak link:

JS Stand-in: reference counts and a cycle

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Virtual functions and the vtable

Q: How do virtual functions work? A class with virtual functions gets a vtable: one table per class of pointers to its virtual function implementations. Each object carries a hidden pointer (the vptr) to its class's table. A call through a base pointer or reference compiles to "follow the vptr, index the table, jump", which is dynamic dispatch chosen by the object's real type, not the pointer's static type. (The exact layout is an implementation detail, but this is the universal mechanism.)

C++
struct Shape {
    virtual double area() const = 0;        // pure virtual: Shape is abstract
    virtual ~Shape() = default;             // virtual destructor: required for delete via base pointer
};
struct Circle : Shape {
    double r;
    explicit Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }   // 'override' catches typos
};

std::unique_ptr<Shape> s = std::make_unique<Circle>(2);
s->area();                                  // runs Circle::area through the vtable

Be ready for these follow-ups: why a base class destructor must be virtual (deleting a derived object through a base pointer without it is undefined behavior); slicing (copying a Circle into a Shape by value cuts off the derived part and the polymorphism); why constructors cannot be virtual (the vptr is not set up yet); what happens when you call a virtual function from a constructor (it resolves to the version of the class being constructed, not the most derived one); and the cost (one extra indirection per call and the vptr per object).

JS Stand-in: a hand-made vtable

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does std::move(x) do by itself?

    std::move performs no move. It only allows overload resolution to pick the move operations, and those do the transfer.
  2. 2. Why should a polymorphic base class have a virtual destructor?

    Without it, the base destructor runs but the derived part is not properly destroyed, and the standard calls the deletion undefined.
  3. 3. Which is the best default for exclusive ownership of a heap object?

    unique_ptr expresses single ownership at no extra cost and cleans up automatically.
  4. 4. Two objects hold std::shared_ptr to each other. What happens?

    Each object keeps the other alive. Make one link a weak_ptr to break the cycle.

Summary

  • RAII ties cleanup to object lifetime, so scopes and exceptions release resources automatically.
  • Prefer the rule of zero; if you manage a resource yourself, write all five special members and make moves noexcept.
  • std::move is a cast; the move operations do the stealing and leave a valid but unspecified source.
  • unique_ptr is the default owner, shared_ptr is for shared ownership, weak_ptr breaks cycles.
  • Virtual calls use a per-object vptr into a per-class vtable; base classes need virtual destructors, and slicing loses polymorphism.

Next: Operating Systems: Processes, Threads and Deadlocks.