Modern C++ • C++20 baseline
Designing C++ APIs and Library Boundaries
Expose stable concepts and avoid leaking implementation details without a reason.
A library API should communicate ownership, mutation, errors, and lifetime. Use value types for small self-contained data, references for required non-owning access, and smart pointers when ownership semantics demand them. Avoid exposing concrete container choices in stable interfaces unless that choice is part of the contract.
Key points
- Use const correctness to show read-only access.
- Opaque implementation patterns can reduce rebuilds and ABI exposure.
Example
#include <memory>
#include <string>
class Document {
public:
static std::unique_ptr<Document> open(const std::string& path);
virtual ~Document() = default;
virtual std::string title() const = 0;
};
What to expect
The interface communicates factory ownership, virtual destruction, and a read-only title query.
Practice exercise
Document whether open can fail by exception, null pointer, or an expected-style result and choose one convention.
Key idea: A useful API states its contracts in types, names, and documentation together.