Namespaces
Variants

std::unique_ptr<T,Deleter>:: reset

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
主模板 unique_ptr<T> 的成员
void reset ( pointer ptr = pointer ( ) ) noexcept ;
(1) (自 C++23 起为 constexpr)
特化版本 unique_ptr<T[]> 的成员
template < class U >
void reset ( U ptr ) noexcept ;
(2) (自 C++23 起为 constexpr)
void reset ( std:: nullptr_t = nullptr ) noexcept ;
(3) (自 C++23 起为 constexpr)

替换被管理的对象。

1,2) 等价于 auto old_ptr = get ( ) ;
/* 将“ptr”赋值给存储的指针 */
if ( old_ptr )
get_deleter ( ) ( old_ptr ) ;
如果 get_deleter ( ) ( old_ptr ) 抛出异常,则行为未定义。
2) 此重载仅当 U pointer 类型相同,或满足以下全部条件时才参与重载决议:
  • pointer element_type* 类型相同。
  • U 是指针类型 V* ,且 V(*)[] 可转换为 element_type(*)[]
3) 等价于 reset ( pointer ( ) )

目录

参数

ptr - 指向要管理的新对象的指针

注释

要替换被管理对象并同时提供新的删除器,可以使用移动赋值运算符。

不执行自重置测试(即检测 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 拥有 Foo 指针(删除器 D)
    std::cout << "Replace owned Foo with a new Foo...\n";
    up.reset(new Foo());  // 为旧对象调用删除器
    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...

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 2118 C++11 unique_ptr<T[]>::reset 拒绝限定转换 接受限定转换
LWG 2169 C++11 存在重载 unique_ptr<T[]>::reset(pointer) 移除该重载

参见

返回指向被管理对象的指针并释放所有权
(公开成员函数)