std::unique_ptr::reset
性病::独特[医]PTR::重置
members of the primary template, unique_ptr | | |
---|---|---|
void reset( pointer ptr = pointer() | (1) | |
members of the specialization unique_ptr<T[]> | | |
void reset( pointer ptr = pointer() | (2) | (until C++17) |
| (3) | |
template< class U > void reset( U ) = delete; | (until C++17) | |
template< class U > void reset( U | (since C++17) | |
| (4) | |
void reset( std::nullptr_t p | (until C++17) | |
void reset( std::nullptr_t p = nullptr | (since C++17) |
替换托管对象。
1%29current_ptr
管理的指针。*this
执行下列操作:
- 保存当前指针的副本。
old_ptr = current_ptr
- 用参数覆盖当前指针。
current_ptr = ptr
- 如果旧指针不是空的,则删除以前托管的对象。
if(old_ptr != nullptr) get_deleter()(old_ptr)
...
2) Behaves the same as the reset member of the primary template. 3) In the specialization for dynamic arrays, std::unique_ptr | (until C++17) |
---|---|
3) Behaves the same as the reset member of the primary template, except that it will only participate in overload resolution if either U is the same type as pointer, or pointer is the same type as element_type* and U is a pointer type V* such that V(*)[] is convertible to element_type(*)[]. 4) Equivalent to reset(pointer()) | (since C++17) |
U
是与pointer
,或
pointer
是与element_type*
和U
是指针类型。V*
使...V(*)[]
可转换为element_type(*)[]
...
4%29相当于reset(pointer())
%28自C++17%29
参数
ptr | - | pointer to a new object to manage |
---|
返回值
%280%29
例外
noexcept
规格:
noexcept
注记
若要在提供新删除项的同时替换托管对象,可以使用移动赋值操作符。
自我重置的测试,即是否ptr
指向已由*this
不执行,除非作为编译器扩展或调试断言提供。注意,代码如p.reset(p.release())
不涉及自重置,只涉及类似的代码p.reset(p.get())
是的。
例
二次
#include <iostream>
#include <memory>
struct Foo {
Foo() { std::cout << "Foo...\n"; }
~Foo() { std::cout << "~Foo...\n"; }
};
struct D {
void operator() (Foo* p) {
std::cout << "Calling delete for Foo object... \n";
delete p;
}
};
int main()
{
std::cout << "Creating new Foo...\n";
std::unique_ptr<Foo, D> up(new Foo(), D() // up owns the Foo pointer (deleter D)
std::cout << "Replace owned Foo with a new Foo...\n";
up.reset(new Foo() // calls deleter for the old one
std::cout << "Release and delete the owned Foo...\n";
up.reset(nullptr
}
二次
产出:
二次
Creating new Foo...
Foo...
Replace owned Foo with a new Foo...
Foo...
Calling delete for Foo object...
~Foo...
Release and delete the owned Foo...
Calling delete for Foo object...
~Foo...
二次
另见
release | returns a pointer to the managed object and releases the ownership (public member function) |
---|
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。