Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1015821
  • 博文数量: 243
  • 博客积分: 3053
  • 博客等级: 中校
  • 技术积分: 2975
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-02 21:11
文章分类

全部博文(243)

文章存档

2013年(2)

2012年(20)

2011年(5)

2010年(114)

2009年(102)

我的朋友

分类:

2010-12-13 16:55:09

在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位于头文件中

#include
#include

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

 int main() {
   auto_ptr ptr1(new MyClass(1));            
   auto_ptrptr2(new MyClass(2));
   ptr1->myFunc();          
   ptr2->myFunc();
   cout<<"test 1 done"<    
   ptr2 = ptr1;
   ptr2->myFunc();          
   //ptr1->myFunc();//取消注释会发生段错误或未定义结果
    cout<<"test 2 done"<   
   MyClass* ptr = ptr2.get();          
   ptr->myFunc();           
     ptr2.reset(new MyClass(3));
   ptr2->myFunc();
   ptr->myFunc(); //此处会产生未定义的结果
   cout<<"test 3 done"<   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容器中。

使用auto_ptr要知道:
1. 智能指针不能共享指向对象的所有权
2. 智能指针不能指向数组。因为其实现中调用的是delete而非delete[]
3. 智能指针不是万能的
4. 智能指针不能作为容器类的元素。例如:
template
void container::insert(const T &value)
{
  ..........
  X = value;
  ..........
}
事实上在stl中,所有的container要内部拷贝所传参数的值时都是传的const类型的值。因此无法用auto_ptr传进去。

因为std::auto_ptr是转移语义,而STL容器的元素必须是值语义,也就是拷贝语义的。
比如,STL容器都是以副本的形式来保存元素。
std::vector v;
int a = 1;
v.push_back(a);
v[0]也是值为1的int,但不是a..仅仅是一个副本.a的值也并未被改变.

再来看std::auto_ptr
std::auto_ptr p1(new int);
std::auto_ptr p2 = p1;
p2的构造修改了p1的值,使p1交出了对动态分配的int的引用权.此时p1不再引用动态int.这就是转移语义.

从语义上,这两个就不兼容.
另外,std::auto_ptr为了达到转移语义的要求,只提供了这样的一个拷贝构造函数
auto_ptr(auto_ptr&); 而不是通常情况看到的T(const T&); 这就是一个非值语义的表现.

而std::vector因为对元素类型要求是值语义的,所以必须要求元素类型提供T(const T&)的拷贝构造函数.
一句话: //一句话,假定有一个动态分配的int空间,则在一个时刻只能有一个auto_ptr指针指向他!
这就是所有权的独占性

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类似 。下面通过示例来介绍shared_ptr的使用:

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

#include
#include
#include
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 <   void myFunc() {cout<<"myFunc() done.  "<< i < };            

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

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

   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、其他一些智能指针介绍

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

阅读(2548) | 评论(0) | 转发(0) |
0

上一篇:Vc++ debug跟release

下一篇:WM_DESTROY&WM_QUIT

给主人留下些什么吧!~~