Introduction and code examples of C++ smart pointers

A C++ smart pointer is a special pointer type that automatically manages the memory of dynamically created objects. Smart pointers can help avoid memory leaks and null pointer exceptions.

The C++ standard library provides three types of smart pointers: unique_ptr, shared_ptr, and weak_ptr.

  1. unique_ptr

unique_ptr is an exclusive smart pointer, which manages the sole ownership of an object, and only one unique_ptr can point to it at a time. When the unique_ptr object is destroyed, the object it manages is also destroyed.

unique_ptr usage sample code:

#include <memory>
#include <iostream>

int main() {
    
    
    std::unique_ptr<int> p1(new int(10));
    std::unique_ptr<int> p2 = std::move(p1);
    std::cout << *p2 << std::endl;   // 输出:10
    return 0;
}
  1. shared_ptr

shared_ptr is a shared smart pointer, which can have multiple pointers pointing to the same object. Each pointer has its own counter, and when the counter reaches 0, the object will be destroyed.

shared_ptr usage sample code:

#include <memory>
#include <iostream>

int main() {
    
    
    std::shared_ptr<int> p1(new int(10));
    std::shared_ptr<int> p2 = p1;
    std::cout << *p1 << std::endl;   // 输出:10
    std::cout << *p2 << std::endl;   // 输出:10
    return 0;
}
  1. weak_ptr

weak_ptr is a weak reference smart pointer, which points to an object managed by shared_ptr, but does not increase the reference count of the object. It automatically becomes a null pointer when the object it points to has been destroyed.

weak_ptr usage sample code:

#include <memory>
#include <iostream>

int main() {
    
    
    std::shared_ptr<int> p1(new int(10));
    std::weak_ptr<int> p2 = p1;
    std::cout << p2.use_count() << std::endl;   // 输出:1
    p1.reset();
    std::cout << p2.use_count() << std::endl;   // 输出:0
    return 0;
}

The above is the introduction and code examples of C++ smart pointers.

Guess you like

Origin blog.csdn.net/qq_39506862/article/details/130893938