AK (short for Andreas Kling) is SerenityOS’s custom C++ standard library implementation. It provides a comprehensive set of modern, memory-safe data structures and utilities that replace the C++ STL throughout the codebase. AK contains 186+ header files offering containers, smart pointers, string handling, error handling, and more.
AK is designed to be used both in userspace and the kernel (with appropriate restrictions). Headers that cannot be used in the kernel are explicitly marked.
Dynamic array container with inline capacity optimization.
#include <AK/Vector.h>Vector<int> numbers;numbers.append(1);numbers.append(2);numbers.append(3);// With inline capacity (no heap allocation for small sizes)Vector<int, 16> small_vec; // First 16 elements stored inline
#include <AK/HashTable.h>HashTable<String> unique_names;unique_names.set("Alice"_string);unique_names.set("Bob"_string);if (unique_names.contains("Alice"_string)) { // Alice is in the set}
#include <AK/Error.h>ErrorOr<int> divide(int a, int b) { if (b == 0) return Error::from_string_literal("Division by zero"); return a / b;}// Using TRY macro (returns on error)ErrorOr<void> example() { auto result = TRY(divide(10, 2)); // result = 5 return {};}// Using MUST (asserts on error, use when error is impossible)auto result = MUST(divide(10, 2));
// From errnoauto err = Error::from_errno(ENOENT);// From string literalauto err = Error::from_string_literal("File not found");// From syscallauto err = Error::from_syscall("open"sv, -1);
#include <AK/Format.h>// Print to stdoutoutln("The answer is {}", 42);// Print to stderr warnln("Warning: {} failed", operation);// Debug output (only in debug builds)dbgln("Debug: value = {}", value);// Format to stringauto str = MUST(String::formatted("Hello {}", name));
#include <AK/Function.h>Function<int(int, int)> add = [](int a, int b) { return a + b; };auto result = add(2, 3); // 5void execute(Function<void()> callback) { callback();}
String: Owned, immutable strings. Use for storage and return values.
StringView: Non-owning views. Use for function parameters.
StringBuilder: Building strings incrementally. Use when concatenating.
ByteString: Deprecated, avoid in new code.
Smart pointer selection
NonnullRefPtr: Shared ownership, cannot be null
RefPtr: Shared ownership, can be null
NonnullOwnPtr: Exclusive ownership, cannot be null
OwnPtr: Exclusive ownership, can be null
Error handling patterns
// Use TRY in functions that return ErrorOrErrorOr<void> my_function() { auto result = TRY(fallible_operation()); return {};}// Use MUST when error is impossibleauto str = MUST(String::from_utf8("valid UTF-8"sv));// Check errors explicitly when neededif (auto result = operation(); result.is_error()) { handle_error(result.error());}