Sign in with Google to keep private notes

C++ API Design

C++ API Design Tips and Tricks

Jason Turner, CppCon 2022 — Back to Basics: API Design.
Goal: Make incorrect API usage difficult to write, preferably (in general) by catching mistakes at compile time.

1. Make a function's intent and contract explicit

// Ambiguous name; callers can silently discard the result.
bool empty() const;

// Clear query; discarded result triggers a compiler diagnostic.
[[nodiscard("check whether the container is empty")]]
bool is_empty() const noexcept;
  • Good names distinguish queries from actions (is_empty() checks; it does not clear).
  • [[nodiscard]] requests a warning when a result is ignored; it is not a compilation error. Put it on functions, types, or selected constructors (C++20); it also works on lambdas (C++23).
  • noexcept promises that no exception escapes. If one does, std::terminate() is called. Use only when the contract really is non-throwing.
  • constexpr permits compile-time evaluation when requirements are met; enable it when the function can meaningfully support it.
struct [[nodiscard]] Error { /* ... */ };     // Ignoring an Error result warns.
struct Lock {
    [[nodiscard]] Lock(int file_descriptor);   // Discarded temporary warns (C++20).
};

2. Never return a raw pointer

Widget* make_widget(int type);     // Who deletes this? Could it be shared?

[[nodiscard]] std::unique_ptr<Widget>
make_widget(WidgetType type);      // Caller receives ownership; automatic cleanup.
  • A raw pointer does not communicate ownership clearly. Prefer returning an object by value, an owning smart pointer, or an explicit non-owning view/reference, depending on the contract.
  • std::unique_ptr<T> means unique ownership and releases its resource at scope exit (RAII).

A resource-specific deleter

std::unique_ptr<T, Deleter> is the signature for smart pointers. We can get a bit creative and supply our smart pointer with a custom delete operation that automatically calls fclose() when going out of scope and the destructor is called.

using FilePtr = std::unique_ptr<
    FILE,
    decltype([](FILE* f) { std::fclose(f); })
>;

[[nodiscard]] FilePtr open_file(/* validated inputs */);
// FilePtr 

Feature was introduced after C++ 20.

3. Replace unrestricted arguments with domain types

// Every int is accepted, though only a few values are meaningful.
[[nodiscard]] std::unique_ptr<Widget> make_widget(int type);

enum class WidgetType { Slider, Button };
[[nodiscard]] std::unique_ptr<Widget> make_widget(WidgetType type);

An enum class rejects ordinary integers implicitly. It is not perfect validation: static_cast<WidgetType>(-42) can still construct a value with no corresponding named enumerator.

When the chosen type can be known at compile time, another design is a constrained factory.

constrained factory (std::is_base_of_v)

template<typename WidgetType>
[[nodiscard]] WidgetType make_widget()
  requires (std::is_base_of_v<Widget, WidgetType>);

The original had the following problems:

  1. You can pass an -42 or whatever to WidgetType

  2. It passes WidgetType and that means if there's a subclass it will lose those methods

  3. A unique pointer will force everything onto the heap. Which is bad news for performance engineers.

The constrained factory:

  1. Allows you to pass in the actual child class you want and use all its methods via templating <typename WidgetType>

  2. Now it's returned by value so its not on the heap anymore

4. Killiing implicit conversions [USE STRONG TYPES]

Implicit conversions between const char *, string, string_view and path break type safety.

// Both arguments accept C strings; reversed arguments can still compile.
FilePtr open_file(const std::filesystem::path& path,
                  std::string_view mode);

auto f = open_file("rb", "/tmp/data"); // Wrong order, potentially compiles!

Force explicit.

Solution 1: Deleted catch-all overload

Please use sparingly.

FilePtr open_file(const std::filesystem::path&, std::string_view);
void open_file(const auto&, const auto&) = delete; // C++20

When non-matching but castable arguments are provided, this line of code will overload the function and so that they throw an error and fail to compile. Use sparingly: it also rejects convenient conversions. clang-tidy has bugprone-easily-swappable-parameters.

Important qualification: File modes may have platform-specific combinations, so a fixed enum does not always capture every valid mode.

Solution 2: Stronger types

// Domain-specific representation, where a finite mode set is appropriate.
enum class FileMode { Read, Write, Append };
FilePtr open_file(const std::filesystem::path&, FileMode);

// Or make a user-defined converting constructor explicit.
struct UserId {
    explicit UserId(int value) : value(value) {}
    int value;
};
// void lookup(UserId);
// lookup(42);          // Rejected: explicit construction required.
// lookup(UserId{42});  // Accepted.

5. Make failure reporting consistent and informative

  • Avoid error reporting that requires a separate get_last_error() because you lose the multithreading ability. Also no one does this.
  • Don't defer error throwing to std::optional<T> because your error catching becomes a bunch if statements to check if an error happened

6. Let parameter types express nullability and lifetime needs

void inspect(const std::string& text);   // Required non-null object; no copy.
void inspect_optional(const std::string* text); // Optional single object; check null.
void process(int count);                  // Small, trivial value: pass by value.
  • Prefer const T& for a required, non-small/non-trivial input and T for small, cheap-to-copy values.
  • A raw T* parameter should normally mean optional, non-owning access to one object. Handle the nullptr case; don't dereference an unchecked nullable pointer.
  • Don't require shared_ptr<T> merely to read a T: that unnecessarily restricts callers.
void print(const std::string& s);                // Only needs the string.
void retain(std::shared_ptr<const std::string> s); // Intentionally shares lifetime.

Pass a smart pointer when the function participates in ownership or lifetime, not merely because the caller happens to own one.

7. Fuzz your API

https://github.com/google/fuzztest

  • Deliberately swap arguments, ignore results, pass invalid enum values or null pointers, and probe failure paths.
  • Run fuzzers with AddressSanitizer and UndefinedBehaviorSanitizer to discover unexpected inputs and internal misuse.
  • Restrict the set of accepted inputs where the domain allows it; prefer invalid usage to fail at compile time rather than at runtime.

One-line design test: Can a caller express a mistake that the type system, interface, or compiler should have rejected? If yes, tighten the contract before relying on documentation.

Other stuff:

  1. Only pass in pointers for singular optional arguments. Those are the only times you'd want to be able to check for nullptr

  2. Otherwise if you want to do things by reference pls use & for non-small, non-trivial objects

Articles to read next