Ownership, RAII and the Rule of Five

Every C++ interview at a trading firm eventually arrives at ownership, usually through a small class that holds a resource. The question behind all of them is the same: for this object, who frees the thing it holds, and at exactly which point in the program?

RAII in one sentence

Tie the lifetime of a resource to the lifetime of an object, so that acquiring it is construction and releasing it is destruction. The acronym is unhelpful and the idea is not: because destructors run deterministically when scope ends, including when an exception unwinds the stack, a resource held this way cannot be leaked by any control path that leaves the scope.

class FileHandle {
public:
    explicit FileHandle(const char* path) : fd_(::open(path, O_RDONLY)) {
        if (fd_ < 0) throw std::runtime_error("open failed");
    }
    ~FileHandle() { if (fd_ >= 0) ::close(fd_); }
private:
    int fd_;
};

The rest of this lesson is for subscribers

Unlock every lesson in Systems Programming for Trading, and every other premium course.

Subscribe to continue

Test your knowledge

Questions are only available to subscribers.

Keep reading Systems Programming for Trading

19 lessons in this course, and every other premium course, on one subscription.

  • Every lesson in every course, with the worked examples and interactive simulators
  • Graded questions on every lesson, with explanations for the wrong answers as well as the right one
  • The trainers, timed assessments and brainteaser library that go with them