ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C++ Tutorial• 8 min read

Modern Smart Pointers: std::unique_ptr & std::shared_ptr

Eliminating raw new/delete and memory leaks via ownership semantics

In Modern C++, raw new and delete are considered anti-patterns. Smart pointers automatically manage heap object lifecycles through strict ownership semantics.

Unique vs Shared Ownership

std::unique_ptr<T>: Represents exclusive ownership. Cannot be copied, only moved (std::move). Incurs ZERO runtime overhead compared to a raw pointer. Automatically frees memory when it leaves scope.

std::shared_ptr<T>: Represents shared reference-counted ownership. Memory is freed only when the last shared_ptr pointing to the object is destroyed.

Always use std::make_unique<T>() and std::make_shared<T>() factory functions for exception safety.

Exclusive Ownership with std::unique_ptr
#include <iostream>
#include <memory>

class Resource {
public:
    Resource() { std::cout << "Resource acquired." << std::endl; }
    ~Resource() { std::cout << "Resource destroyed automatically!" << std::endl; }
    void execute() { std::cout << "Processing data..." << std::endl; }
};

int main() {
    // Allocate heap object with exclusive ownership
    auto ptr = std::make_unique<Resource>();
    ptr->execute();

    // Memory is freed automatically here! Zero leaks!
    return 0;
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which smart pointer represents exclusive single ownership and cannot be copied in C++?