i write a handle class using C++. But when i run my code, i met an error.
#pragma once
#include <iostream>
using std::cout;
using std::endl;
class BaseItem{
public:
virtual BaseItem* clone()
{
return new BaseItem(*this);
}
virtual void sayHello()
{
cout<<"Hello, I am class BaseItem!"<<endl;
}
};
class ChildItem:public BaseItem{
public:
ChildItem* clone()
{
return new ChildItem(*this);
}
void sayHello(){
cout<<"Hello, I am class ChildItem!"<<endl;
}
};
template <typename T>
class Handle
{
public:
Handle():baseItem(NULL), refCount(new size_t(0)) {}
Handle(T& object):baseItem(object.clone()), refCount(new size_t(1)) {}
Handle(const Handle<T>& other):baseItem(other.baseItem), refCount(new size_t(1)) {}
Handle& operator= (const Handle<T>& other)
{
++*other.refCount;
dec_count();
baseItem = other.baseItem;
refCount = other.refCount;
return *this;
}
const T* operator->() const {return baseItem;};
const T& operator*() const {return *baseItem;};
T* operator->() {return baseItem;};
T& operator*() {return *baseItem;};
virtual ~Handle(void)
{
dec_count();
}
private:
T *baseItem;
std::size_t* refCount;
void dec_count()
{
if (-- *refCount == 0 && baseItem != NULL)
{
delete baseItem;
delete refCount;
}
}
};
This is the main function :
int _tmain(int argc, _TCHAR* argv[])
{
BaseItem item1;
ChildItem item2;
vector<Handle<BaseItem> > vec;
vec.push_back(Handle<BaseItem>(item1));
vec.push_back(Handle<BaseItem>(item2));
//for (vector<Handle<BaseItem> >::iterator iter = vec.begin();
// iter != vec.end(); iter++)
//{
//
//}
return 0;
}
when i run the code, the code crashed. i have no idea to debug the code. This is the error: