std::shared_ptr<T>::reset
来自cppreference.com
< cpp | memory | shared ptr
| void reset() noexcept; |
(1) | (C++11 起) |
| template< class Y > void reset( Y* ptr ); |
(2) | (C++11 起) |
| template< class Y, class Deleter > void reset( Y* ptr, Deleter d ); |
(3) | (C++11 起) |
| template< class Y, class Deleter, class Alloc > void reset( Y* ptr, Deleter d, Alloc alloc ); |
(4) | (C++11 起) |
以 ptr 所指向的对象替换被管理对象。能可选地提供删除器 d ,之后在无 shared_ptr 对象占有该对象时以之销毁新对象。默认以 delete 表达式为删除器。始终选择对应提供类型的 delete 表达式,这是函数以使用分离的形参 Y 的模板实现的理由。
若 *this 已占有对象,且它是最后一个占有该对象的 shared_ptr ,则通过所占有的删除器销毁对象。
若 ptr 所指向的对象已被占有,则函数通常会导致未定义行为。
1) 释放被管理对象的所有权,若存在。调用后, *this 不管理对象。等价于 shared_ptr().swap(*this); 。
2-4) 以
ptr 所指向对象替换被管理对象。 Y 必须是完整类型且可隐式转换为 T 。另外:2) 以 delete 表达式为删除器。合法的 delete 表达式必须可用,即 delete ptr 必须为良式,拥有良好定义行为且不抛任何异常。等价于 shared_ptr<T>(ptr).swap(*this); 。
3) 以指定的删除器
d 为删除器。 Deleter 必须对 T 类型可调用,即 d(ptr)必须为良构,拥有良好定义行为且不抛任何异常。 Deleter 必须可复制构造 (CopyConstructible) ,且其复制构造函数和析构函数必须不抛异常。等价于 shared_ptr<T>(ptr, d).swap(*this); 。4) 同 (3) ,但额外地用
alloc 的副本分配内部使用的数据。 Alloc 必须是分配器 (Allocator) 。复制构造函数和析构函数必须不抛异常。等价于 shared_ptr<T>(ptr, d, alloc).swap(*this); 。参数
| ptr | - | 指向要取得所有权的对象的指针 |
| d | - | 为删除对象而存储的删除器 |
| alloc | - | 内部存储所用的分配器 |
返回值
(无)
异常
示例
运行此代码
#include <memory> #include <iostream> struct Foo { Foo(int n = 0) noexcept : bar(n) { std::cout << "Foo: constructor, bar = " << bar << '\n'; } ~Foo() { std::cout << "Foo: destructor, bar = " << bar << '\n'; } int getBar() const noexcept { return bar; } private: int bar; }; int main() { std::shared_ptr<Foo> sptr = std::make_shared<Foo>(1); std::cout << "The first Foo's bar is " << sptr->getBar() << "\n"; // 重置,交与新的 Foo 实例 // (此调用后将销毁旧实例) sptr.reset(new Foo); std::cout << "The second Foo's bar is " << sptr->getBar() << "\n"; }
输出:
Foo: constructor, bar = 1 The first Foo's bar is 1 Foo: constructor, bar = 0 Foo: destructor, bar = 1 The second Foo's bar is 0 Foo: destructor, bar = 0
参阅
构造新的 shared_ptr (公开成员函数) |