std::shared_ptr::reset
void reset(); | (1) | (since C++11) |
|---|---|---|
template< class Y > void reset( Y* ptr ); | (2) | (since C++11) |
template< class Y, class Deleter > void reset( Y* ptr, Deleter d ); | (3) | (since C++11) |
template< class Y, class Deleter, class Alloc > void reset( Y* ptr, Deleter d, Alloc alloc ); | (4) | (since C++11) |
将托管对象替换为ptr.任择删除d可以提供,稍后将用于在shared_ptr物体拥有它。默认情况下,delete表达式用作删除。适配delete始终选择与所提供的类型对应的表达式,这就是为什么使用单独的参数将函数作为模板实现的原因。Y...
如果*this已经拥有了一个对象,这是最后一个shared_ptr拥有它,对象就会通过所拥有的删除器被销毁。
如果指向的对象是ptr该函数将导致未定义的行为。
1%29释放托管对象的所有权(如果有的话)。打完电话后,*this不管理对象。相当于shared_ptr().swap(*this);
2-4%29将托管对象替换为ptr...Y必须是一个完整类型并隐式转换为T.此外:
2%29使用删除表达式作为删除器。有效的删除表达式必须可用,即delete ptr必须有良好的格式,有明确的行为,不抛出任何异常.。相当于shared_ptr<T>(ptr).swap(*this);...
3%29使用指定的删除器。d作为删除者。Deleter类型必须是可调用的。T,即.d(ptr)必须有良好的格式,有明确的行为,不抛出任何异常.Deleter一定是CopyConstructible,并且它的复制构造函数和析构函数不能抛出异常。相当于shared_ptr<T>(ptr, d).swap(*this);...
4%29与%283%29相同,但另外使用alloc用于内部使用的数据分配。Alloc一定是Allocator复制构造函数和析构函数不能抛出异常。相当于shared_ptr<T>(ptr, d, alloc).swap(*this);...
参数
ptr | - | pointer to an object to acquire ownership of |
|---|---|---|
d | - | deleter to store for deletion of the object |
alloc | - | allocator to use for internal allocations |
返回值
%280%29
例外
1%29
noexcept规格:
noexcept
2%29std::bad_alloc如果需要,无法获得额外的内存。可能会为其他错误抛出实现定义的异常。delete ptr如果发生异常,则调用。
3-4%29std::bad_alloc如果需要,无法获得额外的内存。可能会为其他错误抛出实现定义的异常。d(ptr)如果发生异常,则调用。
例
二次
#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";
// reset the shared_ptr, hand it a fresh instance of Foo
// (the old instance will be destroyed after this call)
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二次
另见
(constructor) | constructs new shared_ptr (public member function) |
|---|
© cppreference.com在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

