首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::unique_ptr::reset

members of the primary template, unique_ptr<T>

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执行下列操作:

  1. 保存当前指针的副本。old_ptr = current_ptr
  1. 用参数覆盖当前指针。current_ptr = ptr
  1. 如果旧指针不是空的,则删除以前托管的对象。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<T[]>, this template member is provided to prevent using reset() with a pointer to derived (which would result in undefined behavior with arrays). 4) In the specialization for dynamic arrays, std::unique_ptr<T[]>, this overload is necessary to allow reset to nullptr (which would otherwise be prohibited by the template overload). Equivalent to reset(pointer())

(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)

  1. U是与pointer,或
  1. 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())是的。

二次

代码语言:javascript
复制
#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);      
}

二次

产出:

二次

代码语言:javascript
复制
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)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券