ProblemsMemory ManagementRAII file handle
NoviceMemory Management

RAII file handle

Context

The logging service crashed so often that monitoring started treating it as the baseline. Root cause: file descriptors leak from every early return — the author considered fclose 'optional'. The author has left the company; the descriptors haven't. Wrap the file in a RAII handle so it closes itself no matter what.

Task

Implement a FileHandle class that wraps a raw FILE* and guarantees the file is always closed — even when exceptions are thrown. The class must be movable but not copyable.

Constraints

  • Copy constructor and copy assignment must be deleted
  • Move constructor and move assignment must work correctly
  • Destructor must close the file if open
  • After a move, the source must not close the file (it no longer owns it)
  • Must not throw from the move constructor/assignment

Before you code

  • What is RAII and why does it guarantee cleanup?
  • What must be true of the moved-from object's destructor?
  • Why is noexcept important on move operations?

Tests

  • #1Copy construction does not compile(expects compile error)
  • #2Move transfers ownership, source becomes invalid
  • #3Moved-from destructor does not crash

Hints

Hint 1

Open the file in the constructor with fopen, store the FILE*, and fclose it in the destructor if non-null.

Hint 2

The move constructor should steal the pointer and set the source's pointer to nullptr so it won't double-close.

Editorraii-file-handle.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.