Smart pointer 智能指针小总结

Smart pointer

 line 58之后smart pointer里的计数已经是0,所以会真正释放它引用的对象,调用被引用对象的析构函数。如果继续用指针访问,会出现如下图的内存访问异常。所以说如果选择了用智能指针,就不要再试图用其他方式再去访问对象了。

 1 // sharedTest.cpp : Defines the entry point for the console application.
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <boost/make_shared.hpp>
 6 #include <vector>
 7 //using namespace std;
 8 using namespace boost;
 9 
10 #define SMART_PTR shared_ptr 
11 
12 class Based
13 {
14 protected:
15     int a;
16     char* pa;
17 
18 public:
19     Based():a(0)
20     {
21         pa = new char[10];
22     }
23 
24     void Func(){ std::cout<<"Func "<<a<<std::endl; }
25     virtual ~Based()
26     {
27         delete[] pa;
28         std::cout<<"deconstrctor"<<std::endl;
29     }
30 };
31 
32 
33 
34 class Foo : public Based
35 {
36 private:
37     int b;
38 
39 public:
40     void Test()
41     { 
42         this->b = 100;
43         this->pa[0] = 'b';
44         std::cout<<"Test(), b = "<<this->b<<"this->pa[0] =  "<<this->pa[0]<<std::endl;
45     }
46 
47     ~Foo(){ std::cout<<"~Foo()"<<std::endl;}
48 };
49 
50 int main (int argc, const char * argv[])
51 {
52     Foo * pfoo = new Foo;
53 
54     std::cout<<"{"<<std::endl;
55     {
56       SMART_PTR<Foo> smart_foo(pfoo);
57       smart_foo->Test();
58     }
59     std::cout<<"}"<<std::endl;
60 
61     pfoo->Test();
62 
63     return 1;
64 }
原文地址:https://www.cnblogs.com/dirichlet/p/3227692.html