现在的位置: 首页 > 综合 > 正文

智能指针

2013年09月15日 ⁄ 综合 ⁄ 共 1257字 ⁄ 字号 评论关闭

// Student.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream.h>

class Student
{
public:
Student()
{
cout << "Student()" << endl;
}
~Student()
{
cout << "Student()" << endl;
}
void SayHello()
{
cout << "Hello C++" << endl;
}
};

class RefStudent : public Student
{
int m_nRefCount;
public:
RefStudent()
{
m_nRefCount = 1;
}
int AddRef()
{
return ++m_nRefCount;
}
int Release()
{
m_nRefCount--;

if ( m_nRefCount == 0 )
{
delete this;

return 0;
}
return m_nRefCount;
}
};

class NoAddRefRelase_RefStudent:public RefStudent
{
private:
int AddRef();
int Release();
};

class SmartPtr
{
private:
RefStudent *m_lpStu;
public:
SmartPtr()
{
m_lpStu = NULL;
}
SmartPtr( const SmartPtr& obj )
{
m_lpStu = obj.m_lpStu;

if ( m_lpStu != NULL )
m_lpStu->AddRef();
}
SmartPtr& operator=( const SmartPtr& obj )
{
if ( this == &obj )
{
return *this;
}
else
{
if ( m_lpStu != obj.m_lpStu )
{
if ( m_lpStu != NULL )
m_lpStu->Release();
m_lpStu = obj.m_lpStu;
if ( m_lpStu != NULL )
m_lpStu->AddRef();
}
}
return *this;
}
void CreateObj()
{
if ( m_lpStu == NULL )
{
m_lpStu = new RefStudent;
}
}
NoAddRefRelase_RefStudent* operator->()
{
return (NoAddRefRelase_RefStudent*)m_lpStu;
}
void Release()
{
if ( m_lpStu != NULL)
{
m_lpStu->Release();

m_lpStu = NULL;
}
}
~SmartPtr()
{
Release();
}
};

int main(int argc, char* argv[])
{
SmartPtr sp1;
sp1.CreateObj();

SmartPtr sp2(sp1);
sp2 = sp1;

sp1->SayHello();
sp1.Release();

sp2->SayHello();

//sp1->AddRef();

return 0;
}

抱歉!评论已关闭.