您的位置:首页 > 编程语言 > C语言/C++

理解和使用C++中的智能指针

2012-02-29 13:39 495 查看
           使用C++一个最大的好处是它的动态性。我们可以使用new ,delete 动态分配内存和释放内存。但是有时候就会出现一些问题,如果我们忘记删除用new创建的对象,将会出现内存泄露,在长期运行的系统中,甚至一个很小的内存泄露将会造成很大的问题。所以,怎么样保证每一个new对应一个delete呢?

          一个很好的办法是用C++中的auto_ptr变量。接下来讲使用智能指针来解决这个问题。 在MyAuto_Ptr类中实现智能指针,用类

MyTestObect 测试智能指针。

测试类:MyTestObect

class MyTestObject
{
string name;
int age;

public:
MyTestObject(string s, int a)
{
name = s;
age = a;
cout << "Object created\n";
}

~MyTestObject(void)
{
cout << "Object destroyed\n";
}

string GetName()
{
return name;
}

int GetAge()
{
return age;
}
};智能指针类:MyAuto_Ptr
获取指针template <class T>
class MyAuto_Ptr
{
private:
T *ptr;

public:

//构造函数
explicit MyAuto_Ptr(T *p = 0)
:ptr(p)
{

}

//析构函数
~MyAuto_Ptr(void)
{
delete ptr;
}

//复制构造函数
MyAuto_Ptr(MyAuto_Ptr<T> &source)
{
ptr = source.ptr;

//Since the ownership gets transferred lets point the source to 0
source.ptr = 0;
}

MyAuto_Ptr& operator=(MyAuto_Ptr<T> &source)
{
//check for self reference
if(ptr != source.ptr)
{
//flush the existing memory
delete ptr;
ptr = 0;

// use the new pointer
ptr = source.ptr;

//Since the ownership gets transferred lets point the source to 0
source.ptr = 0;

return *this;
}
}

//获取指针
T& operator *()
{
return *ptr;
}

//

T* operator ->()
{
return ptr;
}

//获取指针的值
T* get()
{
return ptr;
}

//重设指针的值
void reset(T *newVal)
{
delete ptr;
ptr = newVal;
}

//release the pointer and returns the ownership
T* release()
{
T *t = ptr;
ptr = 0;
return t;
}
};

测试代码:
int main(int argc, char* argv[])
{
{//dummy brace to test the destruction
MyAuto_Ptr<MyTestObject> p(new MyTestObject("Rahul Singh", 29));

//test the -> operator
cout << "Name: " << p->GetName() << ", Age: " << p->GetAge() << "\n";

//test the transfer of ownership in copy constructor
MyAuto_Ptr<MyTestObject> p2(p);

//test the * operator
cout << "Name: " << (*p2).GetName() << ", Age: " << (*p2).GetAge() << "\n";

//test the transfer of ownership in assignment operator
MyAuto_Ptr<MyTestObject> p3;
p3 = p2;

//test the get function
cout << "Name: " << p3.get()->GetName() << ",
Age: " << p3.get()->GetAge() << "\n";

//lets test the reset function
p3.reset(new MyTestObject("Megha Singh", 28));

//test the get function
cout << "Name: " << p3.get()->GetName() << ",
Age: " << p3.get()->GetAge() << "\n";

//finally lets test the release function
MyAuto_Ptr<MyTestObject> p4(p3.release());

cout << "Name: " << p4.get()->GetName() << ",
Age: " << p4.get()->GetAge() << "\n";
}
getchar();
return 0;
}

复制搜索

复制搜索
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息