Langsung ke konten
Skillpedia
Pemrograman umum48k Β· #5888

cpp

Fungsinya

Panduan ini membantu Anda menulis kode C++ yang lebih modern, aman, dan efisien. Panduan ini menunjukkan cara menerapkan praktik terbaik untuk mengelola memori, tipe data, penanganan error, serta menjalankan banyak proses secara bersamaan.

Kapan dipakai

  • βœ“Saat mempelajari C++ modern.
  • βœ“Saat meninjau kode C++ yang sudah ada.
  • βœ“Saat menulis kode C++ yang harus cepat dan aman.

Link skill

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

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/cpp/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit β†’

Contoh permintaan ke AI

β€œBagaimana cara mengelola memori di C++ dengan aman?”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Panduan ini membandingkan contoh kode 'buruk' dengan contoh C++ yang 'baik'. Panduan ini juga menjelaskan mengapa pendekatan modern lebih baik untuk menghindari kesalahan umum dan meningkatkan performa.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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) { ... }

…
Pertanyaan umum

Apa itu 'RAII'?

RAII singkatan dari 'Resource Acquisition Is Initialization'. Ini adalah teknik C++ di mana resource (seperti memori atau file) dikelola secara otomatis saat sebuah objek dibuat atau dihancurkan. Contohnya, file otomatis ditutup ketika objek yang mewakilinya keluar dari cakupan (scope).

Mengapa menggunakan `std::vector` alih-alih `new int[n]`?

`std::vector` mengelola memori secara otomatis, sehingga Anda tidak perlu repot mengalokasikan dan membebaskan memori secara manual yang bisa menimbulkan error. Selain itu, `std::vector` juga menawarkan fitur yang lebih berguna.

Apa itu 'move semantics'?

Move semantics adalah cara untuk mengoptimalkan perpindahan resource (seperti blok data berukuran besar) antar objek. Alih-alih menyalin semuanya yang bisa memakan waktu, kepemilikan resource 'dipindahkan', sehingga prosesnya jauh lebih cepat.

Detail

Deskripsi asli dari pembuat

Language-specific super-code guidelines for cpp.

repo: sickn33/agentic-awesome-skills

Popularitas

Bintang GitHub
48k
Peringkat
#5888
Lisensi
MIT
Diperbarui
15/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa