How do you assign a value to a shared_ptr in C++?

In C++, you can assign a shared_ptr using the following methods:

  1. Using the assignment operator: You can use the “=” operator to assign one shared_ptr to another shared_ptr. For example:
std::shared_ptr<int> ptr1 = std::make_shared<int>(5);
std::shared_ptr<int> ptr2 = ptr1; // 使用赋值运算符将ptr1赋值给ptr2
  1. With the reset() function, you can assign a shared_ptr to another shared_ptr. For example:
std::shared_ptr<int> ptr1 = std::make_shared<int>(5);
std::shared_ptr<int> ptr2;
ptr2.reset(ptr1.get()); // 将ptr1赋值给ptr2

It’s important to note that if a shared_ptr is already pointing to an object, when it is assigned to another shared_ptr, the original shared_ptr will automatically decrease its reference count. If the reference count reaches 0, the managed object will be released. When the assigned shared_ptr is destructed or assigned a different value, the reference count will increase. This means that resources can be shared using shared_ptr and they will be automatically released when no longer needed.

bannerAds