The pass-key idiom in C++ allows you to have a public constructor while still restricting who can call it. By creating a nested (or standalone template) class whose constructor is private but befriends only the owning class, you can pass an instance of that key as a required constructor argument. This lets utilities like std::make_unique<>() work—since they can forward the key—while preventing unauthorized callers from constructing the object. A reusable template version parametrized on the trusted type is also shown. A C++17 gotcha with empty braces {} is noted, fixed in C++20 by making the constructor explicit.

3m read timeFrom playfulprogramming.com
Post cover image

Sort: