Back to Skills

cpp-smart-pointers

verified

Use when managing memory safely in C++ with smart pointers including unique_ptr, shared_ptr, weak_ptr, and RAII patterns.

View on GitHub

Marketplace

han

TheBushidoCollective/han

Plugin

jutsu-cpp

Technique

Repository

TheBushidoCollective/han
60stars

jutsu/jutsu-cpp/skills/cpp-smart-pointers/SKILL.md

Last Verified

January 24, 2026

Install Skill

Select agents to install to:

Scope:
npx add-skill https://github.com/TheBushidoCollective/han/blob/main/jutsu/jutsu-cpp/skills/cpp-smart-pointers/SKILL.md -a claude-code --skill cpp-smart-pointers

Installation paths:

Claude
.claude/skills/cpp-smart-pointers/
Powered by add-skill CLI

Instructions

# C++ Smart Pointers and RAII

Master C++ smart pointers and Resource Acquisition Is Initialization (RAII)
patterns for automatic, exception-safe resource management. This skill covers
unique_ptr, shared_ptr, weak_ptr, custom deleters, and best practices for
modern C++ memory management.

## RAII Principles

Resource Acquisition Is Initialization is a fundamental C++ idiom where
resource lifetime is tied to object lifetime.

### Core Concept

```cpp
// Bad: Manual resource management
void process_file_bad() {
    FILE* file = fopen("data.txt", "r");
    if (!file) return;

    // ... process file ...
    // If exception occurs, file never closed!

    fclose(file);
}

// Good: RAII with smart pointer
void process_file_good() {
    auto deleter = [](FILE* f) { if (f) fclose(f); };
    std::unique_ptr<FILE, decltype(deleter)> file(fopen("data.txt", "r"), deleter);

    if (!file) return;

    // ... process file ...
    // File automatically closed when unique_ptr destroyed
}

// Even better: Custom RAII wrapper
class FileHandle {
    FILE* file;
public:
    explicit FileHandle(const char* filename, const char* mode)
        : file(fopen(filename, mode)) {
        if (!file) throw std::runtime_error("Failed to open file");
    }

    ~FileHandle() {
        if (file) fclose(file);
    }

    // Delete copy operations
    FileHandle(const FileHandle&) = delete;
    FileHandle& operator=(const FileHandle&) = delete;

    // Allow move operations
    FileHandle(FileHandle&& other) noexcept : file(other.file) {
        other.file = nullptr;
    }

    FileHandle& operator=(FileHandle&& other) noexcept {
        if (this != &other) {
            if (file) fclose(file);
            file = other.file;
            other.file = nullptr;
        }
        return *this;
    }

    FILE* get() const { return file; }
};
```

### RAII Benefits

```cpp
// Exception safety
void transaction() {
    std::lock_guard<std::mutex> lock(mutex); // RAII lock
    std::unique_ptr<Resource> res

Validation Details

Front Matter
Required Fields
Valid Name Format
Valid Description
Has Sections
Allowed Tools
Instruction Length:
22740 chars