AgentSkillsCN

m12-lifecycle

精通 C++ 生命周期管理:RAII、析构函数、静态初始化、五法则。

SKILL.md
--- frontmatter
name: m12-lifecycle
description: "Mastering C++ Lifecycle: RAII, Destructors, Static Initialization, Rule of 5."

C++ Resource Lifecycle

Core Question

When does this die?

  • Stack: End of scope }.
  • Heap: When delete (or smart pointer drop) occurs.
  • Static: At program exit (reverse init order).

Error → Design Question

IssueDesign Question
Resource LeakDid you manually open() without a wrapper class?
Use After FreeDid you capture a reference to a local variable in a lambda/thread?
Static FiascoDo statics depend on each other? (Use Meyers Singleton).

Thinking Prompt

  1. Does it have a destructor?

    • Yes → RAII. Good.
    • No → Wrap it.
  2. Does it copy?

    • FILE* cannot copy. Delete copy constructor.

Quick Reference

PatternUse Case
RAII WrapperFileHandle, LockGuard.
Scope Guardstd::scope_exit (Cleanup callback).
Rule of 5Copy/Move/Destructor implementation logic.