Technology Sharing

【C】Smart pointer

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Smart pointers explained

Smart Pointer is a tool in C++ used to automatically manage dynamically allocated memory.

It is a class that encapsulates the functionality of a raw pointer and automatically handles resource allocation and release, helping programmers avoid common memory management errors such as memory leaks, dangling pointers, and other issues.

Smart pointers work through the Resource Acquisition Is Initialization (RAII) mechanism, which means that smart pointers acquire resources when they are constructed and release them when they are destroyed. This ensures that resources are properly released even in abnormal situations.

 

Problems solved by smart pointers

(1) Memory leak: Memory is released manually, and can be released automatically using smart pointers.

(2) Propagation and release of shared ownership pointers, such as the destruction problem when multiple threads use the same object.

 

Several types of smart pointers

The C++ standard library provides several types of smart pointers, including:

  1. std::unique_ptr

    • The exclusive ownership model means that aunique_ptrAn instance has exclusive ownership of the object it points to.
    • whenunique_ptrWhen it goes out of scope or is explicitly reset, it automatically calls its destructor and releases the managed object.
    • Copying is not supported, but moving is possible.
  2. std::shared_ptr

    • Shared ownership model, allowing multipleshared_ptrInstances share ownership of the same object.
    • Use reference counting to keep track of pointers to the same objectshared_ptrquantity.
    • When the lastshared_ptrWhen the instance goes out of scope or is reset, the reference count is reduced to zero, the object's destructor is called, and the object is released.
  3. std::weak_ptr

    • To solveshared_ptrThe circular reference problem.
    • Without increasing the reference count, you can observe thatshared_ptrManages objects but does not participate in their life cycle management.
    • When noshared_ptrWhen an instance points to an object,weak_ptrIt is possible to detect that an object has been destroyed.

The design and use of smart pointers greatly simplifies memory management in C++ and improves the robustness and security of programs. In modern C++ programming, it is strongly recommended to use smart pointers instead of naked pointers to improve the quality and maintainability of code.

 

Smart pointer example

Smart pointers are a means of automatically managing dynamically allocated memory in C++ to prevent memory leaks and other resource management related problems.

std::unique_ptrExample

std::unique_ptrIs a smart pointer with exclusive ownership, which ensures that only onestd::unique_ptrThe instance has control over a given resource.std::unique_ptrWhen it goes out of scope or is reset, the resources it owns are automatically released.

  1. #include <memory>
  2. class MyClass {
  3. public:
  4. MyClass() { std::cout << "MyClass constructor called.n"; }
  5. ~MyClass() { std::cout << "MyClass destructor called.n"; }
  6. void doSomething() { std::cout << "Doing something...n"; }
  7. };
  8. int main() {
  9. // 创建一个unique_ptr来管理MyClass的实例
  10. std::unique_ptr<MyClass> uptr(new MyClass());
  11. // 调用doSomething方法
  12. uptr->doSomething();
  13. // unique_ptr会在离开作用域时自动调用MyClass的析构函数
  14. return 0;
  15. }

std::shared_ptrExample

std::shared_ptris a shared-ownership smart pointer that allows multiplestd::shared_ptrInstances share ownership of the same resources.std::shared_ptrReference counting is used to track how many smart pointers point to the same resource. When the reference count reaches 0, the resource is released.

  1. #include <memory>
  2. class MyClass {
  3. public:
  4. MyClass() { std::cout << "MyClass constructor called.n"; }
  5. ~MyClass() { std::cout << "MyClass destructor called.n"; }
  6. void doSomething() { std::cout << "Doing something...n"; }
  7. };
  8. int main() {
  9. // 创建一个shared_ptr来管理MyClass的实例
  10. std::shared_ptr<MyClass> sptr(new MyClass());
  11. // 创建第二个shared_ptr,共享同一个MyClass实例
  12. std::shared_ptr<MyClass> sptr2 = sptr;
  13. // 调用doSomething方法
  14. sptr->doSomething();
  15. // 当所有shared_ptr实例都超出作用域时,MyClass的析构函数才会被调用
  16. return 0;
  17. }

 

Precautions

In usestd::shared_ptrBe careful to avoid circular references when using , which will cause the reference count to never drop to 0, thus causing resource leaks. In the case of circular references, you can usestd::weak_ptrTo break the cycle,std::weak_ptrDo not increase the reference count, just hold thestd::shared_ptrManages weak references to resources.

These examples show how to use smart pointers to manage dynamically allocated memory to ensure that resources are properly released when appropriate, avoiding common errors that can occur when managing memory manually.

 

Other Examples

https://www.cnblogs.com/god-of-death/p/17962676

https://zhuanlan.zhihu.com/p/678722914