随笔 - 87  文章 - 279  trackbacks - 0
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

潜心看书研究!

常用链接

留言簿(19)

随笔分类(81)

文章分类(89)

相册

ACM OJ

My friends

搜索

  •  

积分与排名

  • 积分 - 211874
  • 排名 - 116

最新评论

阅读排行榜

评论排行榜

智能指针源码,可像普通指针一样使用,但可以自动释放内存,代码很短,看一下就明白原理了。
#ifndef AUTOPTR
#define AUTOPTR

/**
 * 智能指针类
 
*/

template
<class T>
class AutoPtr {
public :
    AutoPtr(T
* p = 0) : pointee(p) {} //默认构造函数

    template
<class U>
        AutoPtr(AutoPtr
<U>& rhs) : pointee(rhs.release()) {}//复制构造函数

    
~AutoPtr() {delete pointee;}

    template
<class U>
    AutoPtr
<T>& operator=(AutoPtr<U>& rhs) //赋值函数
        if (this != &rhs) {
            reset(rhs.release());
        }

        
return *this;
    }


    T
& operator*() const {return *pointee;} 
    
    T
* operator->() const {return pointee;}

    T
* get() const {return pointee;} //获取dumb pointer

    T
* release() //释放dumb pointer 的拥有权,并返回其值
        T* oldPointee == pointee;
        pointee 
= 0;
        
return oldPointee;
    }
 
    
    
void reset(T* p=0//重复置p指针
        if (pointee != p) {
            delete pointee;
            pointee 
= p;
        }

    }


private :
    T
* pointee;
}
;

#endif AUTOPTR

test.cpp
#include "AutoPtr.h"
#include 
<iostream>
#include 
<string>
using namespace std;

int main() {
    AutoPtr
<int> p = new int;
    
*= 100;
    printf(
"%d\n"*p);

    AutoPtr
<string> sp = new string;
    
*sp = "hello world";
    printf(
"%s\n", sp->c_str());
    
return 0;
}

posted on 2008-04-17 17:01 阅读(976) 评论(3)  编辑 收藏 引用 所属分类: C++之梦

FeedBack:
# re: 智能指针源码 2008-07-11 14:16 fr3@K
你的实现没办法像这样使用:

AutoPtr<int> foo()
{
return AutoPtr<int>(new int);
}

void bar()
{
AutoPtr<int> p = foo();
}
  回复  更多评论
  
# re: 智能指针源码 2008-07-15 19:40 hah
@fr3@K
本来就不应该返回指向局部变量的指针  回复  更多评论
  
# re: 智能指针源码 2008-07-16 01:45 fr3@K
std::auto_ptr 就可以. 请参考这篇 (http://www.gotw.ca/publications/using_auto_ptr_effectively.htm) 的 example 7 的用法说明.

实作上可以参考这里 (http://code.google.com/p/gion/source/browse/branches/0.1/include/gion/auto_array.hpp), 找与 auto_array_ref 相关的代码.  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理