Loading...
Loading...

C++ Smart Pointers Tutorial

Smart pointers in C++ help manage dynamic memory by automatically deallocating resources when no longer needed.

What Are Smart Pointers?

Smart pointers are wrapper classes over raw pointers that ensure proper resource cleanup, preventing memory leaks.

Types of Smart Pointers

  • std::unique_ptr: Owns and manages a single resource.
  • std::shared_ptr: Allows multiple shared ownerships of a resource.
  • std::weak_ptr: Avoids circular references when used with std::shared_ptr.

Usage Examples

Unique Pointer


#include <memory>
#include <iostream>

int main() {
    std::unique_ptr<int> ptr = std::make_unique<int>(10);
    std::cout << *ptr << std::endl; // Outputs: 10
    return 0;
}
                

Shared Pointer


#include <memory>
#include <iostream>

int main() {
    std::shared_ptr<int> ptr1 = std::make_shared<int>(20);
    std::shared_ptr<int> ptr2 = ptr1; // Shared ownership
    std::cout << *ptr2 << std::endl; // Outputs: 20
    return 0;
}
                

Weak Pointer


#include <memory>
#include <iostream>

int main() {
    std::shared_ptr<int> shared = std::make_shared<int>(30);
    std::weak_ptr<int> weak = shared; // Does not increase reference count
    if (auto locked = weak.lock()) {
        std::cout << *locked << std::endl; // Outputs: 30
    }
    return 0;
}
                

Benefits of Smart Pointers

  • Automated memory management.
  • Prevent dangling pointers.
  • Reduce the risk of memory leaks.
0 Interaction
1.4K Views
Views
38 Likes
×
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home