auto_ptr,shared_ptr 智能指针的使用

简介: Q: 那个auto_ptr是什么东东啊?为什么没有auto_array?A: 哦,auto_ptr是一个很简单的资源封装类,是在头文件中定义的。它使用“资源分配即初始化”技术来保证资源在发生异常时也能被安全释放(“exception safety”)。

Q: 那个auto_ptr是什么东东啊?为什么没有auto_array?
A: 哦,auto_ptr是一个很简单的资源封装类,是在<memory>头文件中定义的。它使用“资源分配即初始化”技术来保证资源在发生异常时也能被安全释放(“exception safety”)。一个auto_ptr封装了一个指针,也可以被当作指针来使用。当其生命周期到了尽头,auto_ptr会自动释放指针。例如:
 #include<memory>
 using namespace std;

 struct X {
  int m;
  // ..
 };

 void f()
 {
  auto_ptr<X> p(new X);
  X* q = new X;

  p->m++;  // use p just like a pointer
  q->m++;
  // ...

  delete q;
 }
如果在代码用// ...标注的地方抛出异常,那么p会被正常删除——这个功劳应该记在auto_ptr的析构函数头上。不过,q指向的X类型对象就没有被释放(因为不是用auto_ptr定义的)。详情请见TC++PL 14.4.2节。
Auto_ptr是一个轻量级的类,没有引入引用计数机制。如果你把一个auto_ptr(比如,ap1)赋给另一个auto_ptr(比如,ap2),那么ap2将持有实际指针,而ap1将持有零指针。例如:

 #include<memory>
 #include<iostream>
 using namespace std;

 struct X {
  int m;
  // ..
 };

 int main()
 {
  auto_ptr<X> p(new X);
  auto_ptr<X> q(p);
  cout << "p " << p.get() << " q " << q.get() << "\n";
 }

 
运行结果应该是先显示一个零指针,然后才是一个实际指针,就像这样: 
 p 0x0 q 0x378d0

 
auto_ptr::get()返回实际指针。
这里,语义似乎是“转移”,而非“拷贝”,这或许有点令人惊讶。特别要注意的是,不要把auto_ptr作为标准容器的参数——标准容器要求通常的拷贝语义。例如:

 std::vector<auto_ptr<X> >v; // error

一个auto_ptr只能持有指向单个元素的指针,而不是数组指针:

 void f(int n)
 {
  auto_ptr<X> p(new X[n]); // error
  // ...
 }

 
上述代码会出错,因为析构函数是使用delete而非delete[]来释放指针的,所以后面的n-1个X没有被释放。 
那么,看来我们应该用一个使用delete[]来释放指针的,叫auto_array的类似东东来放数组了?哦,不,不,没有什么auto_array。理由是,不需要有啊——我们完全可以用vector嘛:

 void f(int n)
 {
  vector<X> v(n);
  // ...
 }

 
如果在 // ... 部分发生了异常,v的析构函数会被自动调用。

引入智能指针可以防止出现悬垂指针的情况
一般是把指针封装到一个称之为智能指针类中,这个类中另外还封装了一个使用计数器,对指针的复制等操作将导致该计数器的值加1,对指针的delete操作则会减1,值为0时,指针为NULL

在C++中,内存资源的管理经常是一个令人头痛的问题,指针的错误使用经常是造成内存泄露和“未定义行为”的根源。很多资源被动态分配与heap内而后被用于单一区块或函数内。它们应该在控制流离开那个区块或函数时被释放。智能指针就是针对这种形势而设计的特制产品。它是一种外观和行为都被设计成与内建的指针相类似的对象,不过它提供更多的功能,其析构函数会自动对其所指的对象调用delete来进行删除。

常用的智能指针有auto_ptr(C++标准库提供),shared_ptr(tr1库提供,最为常用),另外还有scoped_ptr,intrusive_ptr,weak_ptr(均为tr1库提供)。在此着重介绍auto_ptr以及shared_ptr两种,在文章最后会对其他智能指针也进行简单的介绍。

1、auto_ptr:它允许程序员创建一个指向某种资源的指针对象,当该对象离开它的作用域时,它所指向的资源也会被自动释放。在此类中对*和->运算符进行了重载,使它可以像指针一样被使用,另外它也提供get(),reset(),release()等方法来供外界取出和重新设置它所指向的对象,详细内容参考[5]以及C++标准库的说明文档。下面通过一个示例来展示auto_ptr的使用。
[code=cpp]//文件名为test_auto_ptr.cpp
//auto_ptr位于<memory>头文件中

#include <memory>
#include <iostream>

using namespace std;         
class MyClass {
public:
     int i;
   MyClass(int s) {i=s;}
   ~MyClass() {cout<<"This class has been destroied. "<<i<<endl;}
   void myFunc() {cout<<"myFunc() done. "<<i <<endl;}
};            

int main() {
   auto_ptr<MyClass> ptr1(new MyClass(1));            
   auto_ptr<MyClass>ptr2(new MyClass(2));
   ptr1->myFunc();          
   ptr2->myFunc();
   cout<<"test 1 done"<<endl;
    
   ptr2 = ptr1;
   ptr2->myFunc();          
   //ptr1->myFunc();//取消注释会发生段错误或未定义结果
    cout<<"test 2 done"<<endl;
   
   MyClass* ptr = ptr2.get();          
   ptr->myFunc();           
     ptr2.reset(new MyClass(3));
   ptr2->myFunc();
   ptr->myFunc(); //此处会产生未定义的结果
   cout<<"test 3 done"<<endl;
   return 0;
}    [/code]

编译并运行:

#g++ -g -o test_auto_ptr test_auto_ptr.cpp

# ./test_auto_ptr

运行结果如下:
myFunc() done. 1
myFunc() done. 2
test 1 done
This class has been destroied. 2
myFunc() done. 1
test 2 done
myFunc() done. 1
This class has been destroied. 1
myFunc() done. 3
myFunc() done. 0
test 3 done
This class has been destroied. 3

从上面的结果可以看出auto_ptr具有智能指针的功能,但是由于auto_ptr被销毁时会自动删除它所指之物,所以一定要注意不要让多个auto_ptr同时指向同一对象,否则一个对象会被删除多次,这会导致“未定义的行为”。另外,auto_ptr在进行复制时会产生一些诡异的行为,如进行ptr2=ptr1;之后ptr2指向对象,而ptr1会被设为NULL,调用ptr1会产生未定义行为(或段错误)。由此也可以看出auto_ptr不能用于STL容器中。

2、shared_ptr:它是一种引用计数型智能指针,它的复制行为相比auto_ptr要正常许多,它也可以被自由用于STL容器中。但是shared_ptr类不属于标准C++库,而是属于tr1库(C++ tr1是针对C++标准库的第一次扩展。即将到来的下一个版本的C++标准c++0x会包括它,以及一些语言本身的扩充),现在的编译器对于tr1库的支持良莠不齐,但是从gcc 4.0开始就实现了对于shared_ptr的支持。shared_ptr的用法和auto_ptr类似,具体参见[1] 。下面通过示例来介绍shared_ptr的使用:

[code=cpp]//文件名为test_shared_ptr.cpp
//shared_ptr位于 <tr1/memory> 头文件中

#include <tr1/memory>
#include <iostream>
#include<vector>
using namespace std;
using std::tr1::shared_ptr;         
class MyClass {
public:
   int i;
   MyClass(int s) {i=s;}
   ~MyClass() {cout<<"This class has been destroied. "<< i <<endl;}
   void myFunc() {cout<<"myFunc() done. "<< i <<endl;}
};            

int main() {

//下面分别建立两个智能指针,然后测试他们的基本使用
//注意不能使用如下形式: shared_ptr<MyClass> ptr = new MyClass(2);
   shared_ptr<MyClass> ptr1(new MyClass(1));            
   shared_ptr<MyClass>ptr2(new MyClass(2));
   (*ptr1).myFunc();          
   ptr2->myFunc();
   cout<<"test 1 done!"<<endl;
    
    
     //下面尝试复制操作,并进行把两个
   ptr2 = ptr1;
   ptr2->myFunc();          
   ptr1->myFunc();
   ptr1.reset();
   cout<<"ptr1.reset() done!"<<endl;
   ptr2.reset();
   cout<<"test 2 done!"<<endl; 
     
      
   MyClass* temp_ptr=new MyClass(3);
   ptr1.reset(temp_ptr);//把普通指针委托给智能指针进行托管          
   ptr1->myFunc(); //注意委托之后不要使用delete,否则程序会出现异常,轻则出错,重则挂掉
    //delete temp_ptr;         
   cout<<"test 3 done"<<endl;
  
  
   //智能指针也可以放入STL容器中,并且不影响其使用
   //注意这里MyClass> 后面有一个空格,否则会被当作一个>>运算符
   vector<shared_ptr<MyClass> > myVector;
         {
     shared_ptr<MyClass> temp_shared_ptr(new MyClass(4));
    myVector.push_back(temp_shared_ptr);
         }//离开temp_shared_ptr的作用域,只是它自己析构,MyClass并不会析构
  
   vector<shared_ptr<MyClass> >::iterator itor =myVector.begin();

   (*itor)->myFunc();
   myVector.clear();
   cout<<"test 4 done!"<<endl;

   return 0;
}

[/code]

编译并运行:

# g++ -g -o test_shared_ptr test_shared_ptr.cpp

#./test_shared_ptr

运行结果如下:
myFunc() done. 1
myFunc() done. 2
test 1 done!
This class has been destroied. 2
myFunc() done. 1
myFunc() done. 1
ptr1.reset() done!
This class has been destroied. 1
test 2 done!
myFunc() done. 3
test 3 done
myFunc() done. 4
This class has been destroied. 4
test 4 done!
This class has been destroied. 3

从运行结果中也可以看出shared_ptr 具有很好的资源管理的能力,可以实现理想的复制操作,并且可以和STL容器兼容。在多线程情况下shared_ptr可以达到和c++内置类型同等的安全性。无疑shared_ptr类将是tr1中最常使用的类型。

但是shared_ptr并不是尽善尽美的,它还存在环状引用等问题。在使用shared_ptr时也有一些注意事项需要遵守,否则反而会弄巧成拙。文章[3]中指出了一些shared_ptr的缺点,不防也看看,有些地方说的还是有道理的。

3、其他一些智能指针介绍

scoped_ptr 与auto_ptr类似,但是不允许复制;
intrusive_ptr是shared_ptr侵入式版本。使用情况,内部以及编写好了自己的内部引用计算器的代码,而又没有时间重写它。intrusive_ptr可以从this构造。
weak_ptr是智能指针shared_ptr的观察者。

上面只是对于智能指针的一个简单的介绍和示例的说明,我也是刚开始学习智能指针,希望上面的内容对大家有帮助。

目录
相关文章
|
1月前
|
安全 程序员 编译器
C++中的RAII(资源获取即初始化)与智能指针
C++中的RAII(资源获取即初始化)与智能指针
20 0
|
1月前
|
安全 程序员 C++
C++中的智能指针:从原始指针到现代内存管理
C++中的智能指针:从原始指针到现代内存管理
18 0
|
3月前
|
C++
C++:一文读懂智能指针
C++:一文读懂智能指针
45 0
|
3月前
|
消息中间件 Kubernetes NoSQL
智能指针的种类以及使用场景
智能指针的种类以及使用场景
|
3月前
|
安全 C++
c++11新特性——智能指针详解
c++11新特性——智能指针详解
|
1月前
|
安全 C++ 容器
C++中的智能指针:自动内存管理的利器
C++中的智能指针:自动内存管理的利器
23 0
|
3月前
|
设计模式 Rust Java
【一起学Rust | 设计模式】习惯语法——默认特质、集合智能指针、析构函数
【一起学Rust | 设计模式】习惯语法——默认特质、集合智能指针、析构函数
56 0
|
1月前
|
存储 Rust C++
C++智能指针
【2月更文挑战第14天】介绍C++智能指针
22 0
|
2月前
|
算法 安全 C++
C++ Effective Modern Pointer (智能指针模块)
C++ Effective Modern Pointer (智能指针模块)