📌  相关文章
📜  unique_ptr vs shared_ptr (1)

📅  最后修改于: 2023-12-03 15:35:28.625000             🧑  作者: Mango

unique_ptr vs shared_ptr

Introduction

In modern C++, smart pointers are used to manage dynamically allocated objects. unique_ptr and shared_ptr are two types of smart pointers that are widely used. Understanding their differences and choosing the appropriate one can help to write safer and more efficient code.

unique_ptr

unique_ptr manages a single object and ensures its deletion when it is no longer needed. It has a unique ownership, meaning that no other unique_ptr can share ownership of the same object. unique_ptr is movable but not copyable, which makes its ownership transferable but not shareable.

#include <memory>

int main() {
  std::unique_ptr<int> ptr(new int(42));
  *ptr = 24; // dereference to access the object it manages
  // ptr2 cannot be created, because ownership is unique
  // std::unique_ptr<int> ptr2 = ptr;
  // ownership can be transferred
  std::unique_ptr<int> ptr3 = std::move(ptr);
  return 0;
}
shared_ptr

shared_ptr allows multiple smart pointers to share ownership of the same object. It keeps a reference count of the number of smart pointers pointing to the same object, and the object is deleted when the count reaches zero. shared_ptr can be copied and assigned, which enables sharing ownership of the object between multiple functions or objects.

#include <memory>

int main() {
  std::shared_ptr<int> ptr(new int(42));
  std::shared_ptr<int> ptr2 = ptr; // shared ownership
  *ptr = 24; // dereference to access the object it manages
  return 0;
}
Comparison

unique_ptr and shared_ptr are both useful in different situations.

  • Use unique_ptr when there is only one owner of the object and the ownership must be unique.
  • Use shared_ptr when multiple objects or functions need to share ownership of the same object.

In general, use unique_ptr by default and convert to shared_ptr only when necessary.

Conclusion

unique_ptr and shared_ptr are two powerful tools in modern C++ programming. With their unique features, developers can write safer and more efficient code that better manages dynamically allocated objects.