All Courses
OOP: RAII AND OWNERSHIP

Resource-Managing Classes

Concept Definition

A resource-managing class owns something that must be released: memory, a file, a socket, a lock, or a database connection. Good design makes that ownership visible and cleanup automatic. The class should protect the resource from leaks, double release, and invalid use.

A useful analogy is a lab equipment cabinet. One responsible person checks equipment out and returns it, instead of leaving tools scattered everywhere.

Why It Matters

Resource bugs are often design bugs. If ownership is unclear, every caller must guess who cleans up. That creates leaks, double deletes, and exception failures.

Good resource-managing classes follow RAII. They acquire a resource during construction, provide safe operations, and release the resource during destruction. Better still, they reuse standard library resource managers when possible.

Syntax Block

class ResourceOwner {
private:
    Resource resource; // owned resource wrapper

public:
    explicit ResourceOwner(Resource r); // take ownership
};

Explained Code

Example: Session Owns a Token

#include <memory> // std::unique_ptr, std::make_unique
#include <string> // std::string
#include <utility> // std::move

class Token {
private:
    std::string value;                         // token data

public:
    explicit Token(std::string tokenValue) : value(std::move(tokenValue)) {} // own text
    const std::string& getValue() const { return value; } // safe read
};

class Session {
private:
    std::unique_ptr<Token> token;              // session owns token

public:
    explicit Session(std::string value)
        : token(std::make_unique<Token>(std::move(value))) {} // acquire safely

    const Token& getToken() const { return *token; } // expose non-owning reference
};

Session owns the token and makes cleanup automatic. No caller needs to remember delete.

Key Points / Rules

  • State ownership directly in the class design.
  • Prefer standard library wrappers over raw resource handles.
  • Decide whether copying is allowed, disabled, or implemented as deep copy.
  • Make cleanup automatic through destructors or member destructors.
  • Keep resource owners small and focused.

Common Mistakes

  1. Hiding ownership behind raw pointers. A raw pointer does not say who deletes the object.
  2. Allowing accidental copies of unique resources. Two owners may release the same resource.
  3. Mixing business logic with cleanup logic. Resource owners should have one clear responsibility.
  4. Ignoring failure during acquisition. Construction should fail clearly if the resource cannot be acquired.

Quick Check

  1. What question should you ask before adding a raw pointer member?
  2. Why does Session use std::unique_ptr<Token>?

Viva Answer

A resource-managing class owns a resource and makes cleanup automatic. In modern C++, it should usually use standard library RAII types instead of manual raw ownership.