【C++编程】 智能指针

 

 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

 

enable_shared_from_this

示例1:

 1 #include <memory>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 class Foo : public enable_shared_from_this<Foo>
 6 {
 7 public:
 8     shared_ptr<Foo> getPointer() {
 9         return shared_from_this();
10     }
11 };
12 
13 int main()
14 {
15     auto ptr1 = make_shared<Foo>();
16     auto ptr2 = ptr1->getPointer();
17 }

示例2:

 1 #include <memory>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 class Foo 
 6 {
 7 public:
 8     shared_ptr<Foo> getPointer() {
 9         return shared_ptr<Foo>(this);
10     }
11 };
12 
13 int main()
14 {
15     auto ptr1 = make_shared<Foo>();
16     auto ptr2 = ptr1->getPointer();
17 }

分析:示例2和示例1的使用相同的代码,Foo的该实现将会调用两次析构函数销毁对象释放内存,有两个独立的shard_ptr(ptr1 和ptr2)指向同一个对象,在超过作用域的时间,它们都会尝试调用析构函数删除该对象。

posted @ 2018-05-09 16:19  苏格拉底的落泪  阅读(196)  评论(0编辑  收藏  举报