Z
Zheng Da
Will the following class work well?
If it can not work correctly in some situation, could you help me to
fix it?
Thank you.
//the class will work like the reference in java
//when you create a object, you must save the pointer of the object in
super_auto_ptr
//the class cannot work correctly in multithread
templete<T>
class super_auto_ptr
{
class in_ptr
{
int ref;
T *ptr;
public:
in_ptr(T *p)
{
ptr=p;
ref=1;
}
~in_ptr()
{
delete ptr;
}
};
in_ptr *ptr;
struct super_auto_ptr_ref
{
in_ptr *ptr;
super_auto_ptr_ref(in_ptr *p)
{
ptr=p;
}
};
public:
//the pointer will be saved in in_ptr
super_auto_ptr(T *p)
{
ptr=new in_ptr(p);
}
super_auto_ptr(super_auto_ptr &ref)
{
ptr=ref.ptr;
ptr->ref++;
}
~super_auto_ptr()
{
ptr->ref--;
if(ptr->ref == 0)
delete ptr;
}
super_auto_ptr& operator=(super_auto_ptr &rhs)
{
if(rhs.ptr != this->ptr)
{
this->ptr->ref--;
if(ptr->ref == 0)
delete ptr;
rhs.ptr->ref++;
this->ptr=rhs.ptr;
}
}
T *operator->()
{
return ptr->ptr;
}
T &operator*()
{
return *ptr;
}
super_auto_ptr(super_auto_ptr_ref rhs)
{
this->ptr=rhs.ptr;
this->ptr->ref++;
}
super_auto_ptr &operator=(super_auto_ptr_ref rhs)
{
if(rhs.ptr != this->ptr)
{
this->ptr->ref--;
if(ptr->ref == 0)
delete ptr;
rhs.ptr->ref++;
this->ptr=rhs.ptr;
}
}
operator super_auto_ptr_ref()
{
return super_auto_ptr_ref(ptr);
}
};
If it can not work correctly in some situation, could you help me to
fix it?
Thank you.
//the class will work like the reference in java
//when you create a object, you must save the pointer of the object in
super_auto_ptr
//the class cannot work correctly in multithread
templete<T>
class super_auto_ptr
{
class in_ptr
{
int ref;
T *ptr;
public:
in_ptr(T *p)
{
ptr=p;
ref=1;
}
~in_ptr()
{
delete ptr;
}
};
in_ptr *ptr;
struct super_auto_ptr_ref
{
in_ptr *ptr;
super_auto_ptr_ref(in_ptr *p)
{
ptr=p;
}
};
public:
//the pointer will be saved in in_ptr
super_auto_ptr(T *p)
{
ptr=new in_ptr(p);
}
super_auto_ptr(super_auto_ptr &ref)
{
ptr=ref.ptr;
ptr->ref++;
}
~super_auto_ptr()
{
ptr->ref--;
if(ptr->ref == 0)
delete ptr;
}
super_auto_ptr& operator=(super_auto_ptr &rhs)
{
if(rhs.ptr != this->ptr)
{
this->ptr->ref--;
if(ptr->ref == 0)
delete ptr;
rhs.ptr->ref++;
this->ptr=rhs.ptr;
}
}
T *operator->()
{
return ptr->ptr;
}
T &operator*()
{
return *ptr;
}
super_auto_ptr(super_auto_ptr_ref rhs)
{
this->ptr=rhs.ptr;
this->ptr->ref++;
}
super_auto_ptr &operator=(super_auto_ptr_ref rhs)
{
if(rhs.ptr != this->ptr)
{
this->ptr->ref--;
if(ptr->ref == 0)
delete ptr;
rhs.ptr->ref++;
this->ptr=rhs.ptr;
}
}
operator super_auto_ptr_ref()
{
return super_auto_ptr_ref(ptr);
}
};