#pragma once
class UseCount
{
public:
UseCount(void);
~UseCount(void);
UseCount(const UseCount& useCount);
UseCount& operator= (const UseCount& useCount);
bool IsOnly();
bool reattach(const UseCount& useCount);
private:
int* count;
};
#include "StdAfx.h"
#include "UseCount.h"
UseCount::UseCount(void):
count(new int(1))
{
}
UseCount::~UseCount(void)
{
if(--*count == 0)
{
delete count;
}
}
UseCount::UseCount(const UseCount& useCount)
{
count = useCount.count;
++count;
}
UseCount& UseCount::operator= (const UseCount& useCount)
{
if(--*count == 0)
{
delete count;
}
count = useCount.count;
return *this;
}
bool UseCount::IsOnly()
{
return *count == 1;
}
bool UseCount::reattach(const UseCount& useCount)
{
++*useCount.count;
if(--*count == 0)
{
delete count;
count = useCount.count;
return true;
}
count = useCount.count;
return false;
}
#pragma once
#include "Vector.h"
#include "UseCount.h"
class Handle
{
public:
Handle(void);
~Handle(void);
Handle::Handle(const Handle& handle);
Handle& operator= (const Handle& handle);
private:
Vector* vec;
//int* count;
UseCount useCount;
};
#include "StdAfx.h"
#include "Handle.h"
Handle::Handle(void):
vec(new Vector)
{
}
Handle::~Handle(void)
{
if(useCount.IsOnly())
{
delete vec;
}
}
Handle::Handle(const Handle& handle):
vec(handle.vec)
{
useCount.reattach(handle.useCount);
}
Handle& Handle::operator= (const Handle& handle)
{
if(useCount.reattach(handle.useCount))
{
delete vec;
};
vec = handle.vec;
return *this;
}
653

被折叠的 条评论
为什么被折叠?



