参考链接
https://en.cppreference.com/w/cpp/memory/unique_ptr/reset
对示例中的代码稍作修改,可以看得更清晰
#include <iostream>
#include <memory>
struct Foo // object to manage
{
Foo() { std::cout << "Foo:"<<this<<std::endl; }
~Foo() { std::cout << "~Foo:"<<this<<std::endl; }
};
struct D // deleter
{
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);
}
运行效果