cpp-smart-pointers
БесплатноБез исполняемых скриптовНе проверенUse when managing memory safely in C++ with smart pointers including unique_ptr, shared_ptr, weak_ptr, and RAII patterns.
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
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
// 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
// Exception safety
void transaction() {
std::lock_guard<std::mutex> lock(mutex); // RAII lock
std::unique_ptr<Resource> resource = acquire_resource(); // RAII memory
// If exception thrown, lock released and memory freed automatically
risky_operation();
}
// Automatic cleanup in all paths
std::unique_ptr<int[]> create_buffer(size_t size) {
auto buffer = std::make_unique<int[]>(size);
if (size > max_size) {
return nullptr; // buffer cleaned up
}
initialize(buffer.get(), size);
return buffer; // ownership transferred
}
Unique Ptr
std::unique_ptr provides exclusive ownership of dynamically allocated objects.
Unique Ptr Basic Usage
#include <memory>
// Creating unique_ptr
std::unique_ptr<int> ptr1(new int(42));
auto ptr2 = std::make_unique<int>(100); // Preferred (C++14)
// Array unique_ptr
std::unique_ptr<int[]> arr(new int[10]);
auto arr2 = std::make_unique<int[]>(10); // Preferred
// Custom types
class MyClass {
public:
MyClass(int x, std::string s) : value(x), name(s) {}
void print() const { std::cout << name << ": " << value << std::endl; }
private:
int value;
std::string name;
};
auto obj = std::make_unique<MyClass>(42, "Test");
obj->print();
Ownership Transfer
// Unique_ptr is move-only, not copyable
std::unique_ptr<int> ptr1 = std::make_unique<int>(42);
// std::unique_ptr<int> ptr2 = ptr1; // ERROR: copying deleted
// Move ownership
std::unique_ptr<int> ptr2 = std::move(ptr1);
// ptr1 is now nullptr, ptr2 owns the resource
// Function accepting ownership
void consume(std::unique_ptr<int> ptr) {
std::cout << *ptr << std::endl;
// ptr destroyed here, resource deleted
}
consume(std::move(ptr2)); // Transfer ownership to function
// Function returning ownership
std::unique_ptr<int> create() {
auto ptr = std::make_unique<int>(100);
return ptr; // Move semantics, no explicit std::move needed
}
auto result = create(); // Ownership transferred to result
Custom Deleters
// Function pointer deleter
void custom_delete(int* ptr) {
std::cout << "Deleting: " << *ptr << std::endl;
delete ptr;
}
std::unique_ptr<int, decltype(&custom_delete)> ptr(new int(42), custom_delete);
// Lambda deleter
auto deleter = [](int* ptr) {
std::cout << "Lambda delete: " << *ptr << std::endl;
delete ptr;
};
std::unique_ptr<int, decltype(deleter)> ptr2(new int(100), deleter);
// FILE* with custom deleter
auto file_deleter = [](FILE* f) {
if (f) {
std::cout << "Closing file" << std::endl;
fclose(f);
}
};
std::unique_ptr<FILE, decltype(file_deleter)> file(
fopen("data.txt", "r"),
file_deleter
);
// Socket with custom deleter
struct SocketDeleter {
void operator()(int* socket) const {
if (socket && *socket >= 0) {
close(*socket);
delete socket;
}
}
};
std::unique_ptr<int, SocketDeleter> socket(new int(create_socket()));
Unique Ptr Operations
std::unique_ptr<int> ptr = std::make_unique<int>(42);
// Access
int value = *ptr; // Dereference
i
Установить cpp-smart-pointers в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
BashReadWriteEditFAQ
Что делает скилл cpp-smart-pointers?
Use when managing memory safely in C++ with smart pointers including unique_ptr, shared_ptr, weak_ptr, and RAII patterns.
Как установить скилл cpp-smart-pointers?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл cpp-smart-pointers запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic