How to use std::share_ptr.reset() in C++
时间: 2024-01-21 16:05:08 浏览: 100
In C++, `std::shared_ptr.reset()` is used to reset the `shared_ptr` object and change the ownership of the managed resource. It can be used in the following ways:
1. Reset with a new object:
```cpp
std::shared_ptr<Type> ptr(new Type); // Create a shared_ptr
ptr.reset(new Type); // Reset with a new object
```
2. Reset to nullptr:
```cpp
std::shared_ptr<Type> ptr(new Type); // Create a shared_ptr
ptr.reset(); // Reset to nullptr
```
3. Reset with a custom deleter:
```cpp
std::shared_ptr<Type> ptr(new Type, customDeleter); // Create a shared_ptr with custom deleter
ptr.reset(new Type, customDeleter); // Reset with a new object and custom deleter
```
Remember that after calling `reset()`, the previously managed resource will be released if there are no other shared_ptrs pointing to it. The `reset()` function also updates the reference count accordingly.
阅读全文