skip to content

As a C++ lead, what ownership convention would you set for a codebase's APIs, including who may hold raw pointers?

level: principalimportance: should knowfreq 35%

answer

  1. make ownership visible in types
  2. owning raw pointers banned
  3. borrows end with the call
  4. stored back-pointers need a lifetime proof
  5. values before heap objects

basics

~20 s

Make ownership visible in signatures: std::unique_ptr by value to give or take ownership, T& or T* only to borrow, no owning raw pointers outside a few wrappers, and stored non-owning pointers only where the owner provably outlives the holder.

solid answer

~40 s

I would make every signature answer "who owns this?". Ownership is expressed only by owning types: plain values and containers first, `std::unique_ptr` for heap objects with one owner, `std::shared_ptr` only where lifetime is really shared. Factories return `std::unique_ptr<T>` by value and sinks take it by value. `T&` and `T*` are borrows: never deleted, and not stored past the call unless the code shows the owner outlives the holder — a child's back-pointer to the parent that owns it qualifies, a cached pointer into another subsystem does not. Naked `new` and `delete` are allowed only in a few reviewed low-level files, enforced by a static-analysis rule. The trade-off is migration work and the occasional call cost of moving ownership; the residual risk is dangling borrows, which sanitizer builds in CI catch rather than prevent.

code

cpp · 40 lines
cpp
#include <algorithm>
#include <cstdio>
#include <memory>
#include <string>
#include <vector>

class Node {
public:
    static std::unique_ptr<Node> create(std::string name) {        // returns ownership
        return std::unique_ptr<Node>(new Node(std::move(name)));
    }
    Node& add_child(std::unique_ptr<Node> child) {                  // takes ownership, lends it back
        child->parent_ = this;
        children_.push_back(std::move(child));
        return *children_.back();
    }
    std::unique_ptr<Node> detach(const Node& child) {               // gives ownership back
        auto it = std::find_if(children_.begin(), children_.end(),
                               [&](const auto& c) { return c.get() == &child; });
        if (it == children_.end()) return nullptr;
        auto out = std::move(*it);
        children_.erase(it);
        out->parent_ = nullptr;
        return out;
    }
    Node* parent() const noexcept { return parent_; }               // borrowed, may be null
    const std::string& name() const noexcept { return name_; }
private:
    explicit Node(std::string name) : name_(std::move(name)) {}
    std::string name_;
    Node* parent_ = nullptr;                                         // never owns
    std::vector<std::unique_ptr<Node>> children_;
};

int main() {
    auto root = Node::create("root");
    Node& hud = root->add_child(Node::create("hud"));
    std::unique_ptr<Node> moved = root->detach(hud);
    std::printf("%s parent: %s\n", moved->name().c_str(), moved->parent() ? "set" : "none");
}

go deeper

for a junior

Learn the rule your team uses: smart pointers own, references and raw pointers only borrow.

for a middle

Apply the convention in signatures: by-value unique_ptr for factories and sinks, T& or T* for borrows, and no naked new.

for a senior

Enforce it in review and tooling, and catch the stored raw pointers whose owner is not guaranteed to outlive them.

for a principal

Choose how strict the rule is, how it is enforced, and how a legacy codebase migrates, weighing clarity against migration cost and hot-path call overhead.

## Why this is a lead's decision C++ lets the same `T*` mean "I own this", "I am borrowing this" or "this might be an array", and the compiler cannot tell which. A codebase without a convention ends up with leaks where nobody deleted, double deletes where two parties did, and long arguments in code review. `std::unique_ptr` makes single ownership checkable, but only if the team agrees how the types are used. There is no single right convention; there is a choice of how strict to be and how to migrate. ## A convention that works for most codebases 1. **Values first.** A member that can be a plain value or a container element should be one. Heap allocation through `unique_ptr` is for polymorphic objects, objects that must keep a stable address, optional large parts and compilation firewalls. 2. **Owning types only.** An object on the heap is owned by a `std::unique_ptr` (one owner) or, by exception, a `std::shared_ptr` (lifetime decided at run time by several parties). 3. **Factories return `std::unique_ptr<T>` by value.** The caller can keep it, move it into a container, or convert it to a `std::shared_ptr` — the conversion is one-way. 4. **Sinks take `std::unique_ptr<T>` by value**, so the caller writes `std::move` and the hand-off is visible. 5. **Borrows are `T&` (must exist) or `T*` (may be null)** and never own. A borrow ends with the call unless the owner's lifetime provably encloses the holder's. 6. **No naked `new` or `delete`** outside a short allowlist of low-level files, enforced by a static-analysis rule in CI rather than by reviewers' memory. ## Who may hold a raw pointer The convention's hard part is stored non-owning pointers. A rule that bans them outright is too strict; a rule that allows them anywhere is no rule. A workable middle: | stored raw pointer | allowed? | why | |---|---|---| | a child's pointer to the parent that owns it | yes | the parent destroys the child first, so the back-pointer cannot dangle | | an object borrowing a service owned by an enclosing scope | yes | the scope's destruction order guarantees it | | a cache of pointers into another subsystem's objects | no | nothing ties their lifetimes; use an owner, a handle or a weak reference | | a pointer kept by an asynchronous callback | no | the callback may outlive the object; this needs shared ownership or cancellation | ## Trade-offs to weigh - **Strictness versus migration cost.** A legacy codebase full of owning raw pointers cannot switch at once. Start at module boundaries: new APIs follow the rule, factories begin returning `unique_ptr`, and callers that still need a raw owning pointer call `release()` explicitly, which makes every leftover greppable. - **Clarity versus call cost.** Passing `unique_ptr` by value costs a few instructions per call under common ABIs; for hot non-inlined paths the convention should say "borrow there, transfer ownership at the edges". - **`unique_ptr` versus `shared_ptr` as default.** Making `shared_ptr` the default removes thinking about lifetimes from the author but moves it into debugging: cycles, nondeterministic destruction and atomic counting. Single ownership as the default keeps those costs where they are deliberate. - **Residual risk.** No type system stops a borrow from dangling. Pair the convention with AddressSanitizer builds in CI and with review checklists for stored pointers. ## Exceptions the convention must name Some code legitimately owns through something other than a smart pointer, and a convention that ignores it gets ignored: - **C APIs** that return handles to be freed by a matching function; wrap them once (that is the job of a custom deleter) and expose only the wrapper. - **Arenas and pools**, where one allocator owns every object and frees them together; individual objects are then borrowed by raw pointer or by handle, and nothing deletes them one by one. - **Intrusive structures** and framework types with their own lifetime rules; the convention should state where their boundary is. Listing these exceptions keeps the main rule credible. ## Making it stick - Write the convention down with one example per row, using the codebase's own types. - Add the static-analysis rule and fail the build on new violations, not old ones. - Track the count of remaining owning raw pointers per module and make the number go down. - Review new stored raw pointers explicitly; they are where the convention earns its keep.

  • When is a stored non-owning raw pointer acceptable under such a convention?
    When the code shows by construction that the pointee outlives the holder: a child's back-pointer to the parent that owns it, or an object borrowing a service owned by an enclosing scope. Anything whose lifetime is not tied that way should hold ownership, use a handle validated on access, or move to shared ownership with a weak reference, which is a separate decision with its own cost.
  • How would you roll the convention out in a large legacy codebase full of owning raw pointers?
    Start at the boundaries: new APIs follow it, factories switch to returning `std::unique_ptr` while callers that still need a raw owning pointer call `release()` explicitly, and a static-analysis rule blocks new naked `new` and `delete`. Then migrate module by module, track the count of remaining owning raw pointers, and run sanitizer builds in CI to catch the dangling borrows the conversion exposes.

  • Ban raw pointers entirely, including non-owning parameters
  • Make every heap object a shared_ptr so nobody worries about lifetime
  • Pass unique_ptr by const reference everywhere to avoid copies
  • A stored raw pointer is fine as long as it is checked for null
  • Put every member behind a unique_ptr for consistency