tinycodinglm / cpp /cpp-memory.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
1.36 kB
opencode trace
System You are an expert software engineer.

You are an expert software engineer.

User

Explain C++ smart pointers and memory safety

Assistant

Smart pointers: RAII-based automatic memory management.

std::unique_ptr<T>: exclusive ownership, zero overhead, move-only.

  • std::make_unique<T>(args...) for exception safety
  • Custom deleters: unique_ptr<T, decltype(&free)>

std::shared_ptr<T>: reference-counted shared ownership.

  • std::make_shared<T>: single allocation (control block + object)
  • weak_ptr<T>: non-owning reference, breaks cycles
  • Control block: reference count + weak count + deleter

std::atomic<int> for thread-safe reference counting.

Memory safety issues:

  • Use-after-free: dangling pointers/references
  • Double-free: multiple deletions
  • Buffer overflows: unchecked array access
  • Dangling references: references to destroyed objects

Best practices:

  • Prefer stack allocation and containers
  • Use unique_ptr by default, shared_ptr only when needed
  • Avoid raw new/delete
  • Use std::optional for nullable values
  • std::string_view for non-owning string references