1 #include <iostream>
 2 #include <memory>
 3 
 4 struct Foo
 5 { 
 6     Foo() { std::cout << "Foo...\n"; }
 7     ~Foo() { std::cout << "~Foo...\n"; }
 8 };
 9 
10 struct D
11 {
12     void operator()(Foo *p)
13     {
14         std::cout << "Calling delete for Foo object... \n";
15         delete p;
16     }
17 };
18 
19 int main()
20 {
21     std::cout << "Creating new Foo...\n";
22     
23     //up owns the Foo pointer (deleter D)
24     std::unique_ptr<Foo, D> up(new Foo(), D()); 
25 
26     std::cout << "Replace owned Foo with a new Foo...\n";
27     up.reset(new Foo()); // calls deleter for the old one
28 
29     std::cout << "Release and delete the owned Foo...\n";
30     up.reset(nullptr);
31 }
32 
33 // Creating new Foo...
34 // Foo...
35 // Replace owned Foo with a new Foo...
36 // Foo...
37 // Calling delete for Foo object... 
38 // ~Foo...
39 // Release and delete the owned Foo...
40 // Calling delete for Foo object... 
41 // ~Foo...
View Code

相关文章:

  • 2021-07-12
  • 2021-06-24
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-02
  • 2022-12-23
  • 2022-12-23
  • 2021-11-18
相关资源
相似解决方案