C++

Lesson 02

Smart pointer ownership

Return smart pointers when heap ownership crosses a boundary, and keep raw pointers for non-owning access.

Good Code

src/review_factory.cpp
#include <memory>
#include <string>
#include <utility>

struct Review {
    explicit Review(std::string title) : title(std::move(title)) {}
    std::string title;
};

std::unique_ptr<Review> make_review(std::string title)
{
    // unique_ptr names the single owner of the Review.
    return std::make_unique<Review>(std::move(title));
}

Bad Code

review_factory.cpp
#include <string>
#include <utility>

struct Review {
    explicit Review(std::string title) : title(std::move(title)) {}
    std::string title;
};

Review* make_review(std::string title)
{
    // Raw new leaves callers to guess who must delete the Review.
    return new Review(std::move(title));
}

Review Notes

What to review

Good Code

The good version returns std::unique_ptr<Review>, so the single-owner rule is part of the signature. Callers cannot forget that the object owns heap memory.

Bad Code

The bad version returns a raw pointer from new. Some callers may delete it, some may leak it, and some may pass it around as a borrowed pointer.

Takeaways

  • A C++ API should show ownership in its type: unique_ptr for one owner, shared_ptr for shared lifetime, and raw pointers for observation.