Raw Owning Pointers
Concept Definition
A raw owning pointer is a plain pointer responsible for deleting the object it points to. The problem is that the type does not say ownership clearly. Book* might mean "I own this book" or "I only observe this book."
Think of an unlabeled key on a table. Nobody knows who must return it, so it may be lost or returned twice.
Why It Matters
Raw owning pointers are a major source of leaks, double deletes, and exception-unsafe code. If an exception happens before delete, the resource may leak. If two objects both delete the same pointer, the program has undefined behavior.
Modern C++ has better ownership tools. Use std::unique_ptr for exclusive ownership and std::shared_ptr only when ownership is truly shared.
Syntax Block
auto object = std::make_unique<Type>(); // clear exclusive ownership
Type& view = *object; // non-owning access
Explained Code
Example: Replace Raw Owning Pointer
#include <memory> // std::unique_ptr, std::make_unique
#include <string> // std::string
class Book {
private:
std::string title; // book state
public:
explicit Book(std::string bookTitle) : title(std::move(bookTitle)) {} // initialize
const std::string& getTitle() const { return title; } // safe read
};
class Shelf {
private:
std::unique_ptr<Book> book; // shelf owns one book
public:
Shelf() : book(std::make_unique<Book>("C++ OOP")) {} // allocate safely
const Book& getBook() const { return *book; } // non-owning reference
};
No manual delete appears. The ownership is visible and automatic.
Key Points / Rules
- Avoid raw pointers for ownership.
- Use
std::unique_ptrfor one owner. - Use
std::shared_ptronly for real shared ownership. - Use references for required non-owning access.
- A raw pointer can still be useful for optional non-owning observation, but document it.
Common Mistakes
- Returning raw owning pointers from factory functions. Callers may forget cleanup.
- Storing raw pointers without ownership comments. The next programmer cannot know the contract.
- Mixing smart pointers and manual
delete. Smart pointers should own cleanup. - Using
shared_ptrto avoid thinking about ownership. Shared ownership is not a design shortcut.
Quick Check
- Why is
Book* book = new Book();unclear? - Which smart pointer should you use for one clear owner?
Viva Answer
Raw owning pointers are dangerous because ownership and cleanup are unclear. Prefer RAII types such as std::unique_ptr and standard containers.