shared_ptr reset 返回
时间: 2023-10-10 14:11:25 浏览: 43
shared_ptr 的 reset 函数用于将一个 shared_ptr 对象重置为 nullptr 或者指向另一个对象。它有两个重载形式:
1. `void reset()`: 将 shared_ptr 对象重置为 nullptr,释放它所持有的对象的所有权。
2. `void reset(T* ptr)`: 将 shared_ptr 对象重置为指向 ptr 所指向的对象,释放它原来所持有的对象的所有权。
在第二种情况下,如果传入的指针是一个空指针,则将 shared_ptr 对象重置为 nullptr。reset 函数返回 void,因此不能通过 reset 函数来获取 shared_ptr 对象的引用或指针。
相关问题
shared_ptr reset
shared_ptr的reset()函数用于重置智能指针的指向。当调用reset()时,智能指针会释放当前所拥有的资源,并接管新的资源。
具体来说,当调用reset()时,智能指针会执行以下操作:
1. 释放当前所拥有的资源(如果有的话)。
2. 将智能指针的内部指针指向新的资源。
3. 如果提供了新的资源,智能指针会接管该资源的所有权。
示例代码如下:
```
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> ptr(new int(5));
std::cout << "ptr: " << *ptr << std::endl; // 输出: ptr: 5
ptr.reset(new int(10));
std::cout << "ptr: " << *ptr << std::endl; // 输出: ptr: 10
return 0;
}
```
在上面的示例中,一开始我们创建了一个shared_ptr,指向值为5的整型对象。然后我们调用reset()函数,将智能指针重新指向一个新的整型对象,其值为10。
shared_ptr.reset函数
shared_ptr.reset函数是C++中用于重置shared_ptr指针的成员函数。它的作用是将shared_ptr指针重新指向一个新的对象或者释放当前指向的对象。
当调用reset函数时,它会首先释放当前指向的对象(如果有),然后将shared_ptr指针重新指向一个新的对象或者置为空指针。
reset函数有两种常见的用法:
1. 重置为新的对象:可以将reset函数用于将shared_ptr指针重新指向一个新的对象。例如:
```
shared_ptr<int> ptr(new int(10));
ptr.reset(new int(20));
```
在上述代码中,首先创建了一个shared_ptr指针ptr,指向一个值为10的整数对象。然后通过reset函数将ptr重新指向一个值为20的整数对象。
2. 释放当前对象:可以将reset函数用于释放当前指向的对象,即将shared_ptr指针置为空指针。例如:
```
shared_ptr<int> ptr(new int(10));
ptr.reset();
```
在上述代码中,通过reset函数将ptr置为空指针,从而释放了原来指向的整数对象。
需要注意的是,当使用reset函数重置shared_ptr指针时,如果该指针是最后一个引用该对象的shared_ptr指针,那么该对象会被自动销毁。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)