本文へスキップ
Skillpedia
一般的なプログラミング48k · #5888

cpp

できること

このガイドでは、より現代的で安全、かつ効率的なC++コードの書き方を学べます。メモリの管理、データ型、エラーの処理、複数の処理を同時に扱う方法など、ベストプラクティスを紹介しています。

使う場面

  • ✓モダンなC++を学ぶとき。
  • ✓既存のC++コードを見直すとき。
  • ✓高速で安全なC++コードを書く必要があるとき。

スキルのリンク

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/cpp/SKILL.md

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/cpp/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“C++でメモリを安全に管理するにはどうすればよいですか?”

毎週5つの新しいスキル。1分で読めます。

仕組み

ガイドでは「悪い」コード例と良いC++の例を比較します。現代的な書き方がなぜよりよいのか、よくあるエラーを避けてパフォーマンスを高める理由を説明します。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)をGitHubからそのまま表示しています。

C++: Idiomatic Efficiency Reference

When to Use

  • Use this skill when the task matches this description: Language-specific super-code guidelines for cpp.

Table of Contents

  1. Memory & Ownership
  2. Modern Types & Containers
  3. Move Semantics & References
  4. Templates & Concepts
  5. Error Handling
  6. Concurrency
  7. Anti-patterns specific to C++

1. Memory & Ownership {#memory}

// ❌ Raw new/delete
Widget* w = new Widget();
// ... 15 lines later ...
delete w;

// ✅
auto w = std::make_unique<Widget>();
// ❌ Shared ownership when unique suffices
auto w = std::make_shared<Widget>();
transfer(w); // only one owner

// ✅ — unique_ptr; move when transferring
auto w = std::make_unique<Widget>();
transfer(std::move(w));
// ❌ new[] for dynamic arrays
int* arr = new int[n];
// ... use ...
delete[] arr;

// ✅
std::vector<int> arr(n);
// ❌ Manual RAII wrapper for file/mutex
FILE* f = fopen(path, "r");
// ... must remember fclose ...

// ✅
std::ifstream f(path);
// closes automatically at scope exit
// For non-standard resources: use unique_ptr with custom deleter
auto f = std::unique_ptr<FILE, decltype(&fclose)>(fopen(path, "r"), fclose);

Rule: if you type new, you almost certainly want make_unique or make_shared.


2. Modern Types & Containers {#types}

// ❌ C-style string manipulation
char buf[256];
sprintf(buf, "%s:%d", host, port);

// ✅
auto addr = std::format("{}:{}", host, port); // C++20
// or: auto addr = host + ":" + std::to_string(port);
// ❌ out-parameter for multiple returns
void compute(int input, int& result, std::string& error);

// ✅
struct ComputeResult { int value; std::string error; };
ComputeResult compute(int input);
// or: std::pair / std::tuple with structured bindings
auto [value, error] = compute(input);
// ❌ Manual loop to find element
int idx = -1;
for (int i = 0; i < vec.size(); i++) {
    if (vec[i] == target) { idx = i; break; }
}

// ✅
auto it = std::ranges::find(vec, target); // C++20
// or: std::find(vec.begin(), vec.end(), target);
// ❌ Checking .find() != .end() then accessing
auto it = map.find(key);
if (it != map.end()) { use(it->second); }

// ✅ (C++20)
if (map.contains(key)) { use(map[key]); }
// or keep iterator version when you need the value without double lookup

Use std::string_view for function parameters that don't need ownership.


3. Move Semantics & References {#move}

// ❌ Copying a large container into a function
void process(std::vector<Data> items) { ... } // copies on call

// ✅ — const ref for read, move for sink
void process(const std::vector<Data>& items) { ... }  // read-only
void consume(std::vector<Data> items) { ... }          // sink: caller moves in
// ❌ std::move on const object (silently copies)
const std::string s = "hello";
take(std::move(s)); // still copies

// ✅ — don't const things you intend to move
std::string s = "hello";
take(std::move(s));
// ❌ Returning std::move from local (prevents NRVO)
std::vector<int> build() {
    std::vector<int> v;
    // ... fill ...
    return std::move(v); // pessimization

// ✅ — just return the local; compiler applies NRVO or implicit move
    return v;
}

4. Templates & Concepts {#templates}

// ❌ SFINAE soup
template<typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
T square(T x) { return x * x; }

// ✅ (C++20 concepts)
template<std::integral T>
T square(T x) { return x * x; }
// ❌ Template for one type
template<typename T>
void log(T msg) { std::cout << msg; }
// Only ever called with std::string

// ✅ — don't templatize unless you need multiple types
void log(std::string_view msg) { std::cout << msg; }

Concepts make template errors readable — prefer them over SFINAE and static_assert.


5. Error Handling {#errors}

// ❌ Error codes via int returns (C-style in C++)
int parse(const std::string& input, Data& out);

// ✅ — std::expected (C++23) or exceptions
std::expected<Data, ParseError> parse(const std::string& input);
// or throw for exceptional conditions
Data parse(const std::string& input); // throws ParseError
// ❌ Catching by value (slices derived exceptions)
try { ... }
catch (std::exception e) { ... }

// ✅
catch (const std::exception& e) { ... }

…
よくある質問

「RAII」とは何ですか?

RAIIは「Resource Acquisition Is Initialization(リソースの取得は初期化である)」の略です。メモリやファイルなどのリソースを、オブジェクトの生成と破棄に合わせて自動的に管理するC++の技法です。たとえば、ファイルを表すオブジェクトがスコープを抜けると、ファイルは自動的に閉じられます。

`new int[n]`の代わりに`std::vector`を使うのはなぜですか?

`std::vector`はメモリを自動的に管理するため、メモリの確保や解放を手作業で行う必要がなくなり、そこで起きがちなエラーを防げます。便利な機能も多く備えています。

「ムーブセマンティクス」とは何ですか?

ムーブセマンティクスは、大きなデータ領域などのリソースをオブジェクト間で効率よく受け渡すための仕組みです。すべてをコピーすると時間がかかるため、所有権を「移動」させることで、処理をずっと速くします。

詳細

作者による元の説明

Language-specific super-code guidelines for cpp.

repo: sickn33/agentic-awesome-skills

人気

GitHubのスター
48k
ランキング
#5888
ライセンス
MIT
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル