| re: Does this class will make a pointer in c++ work like the reference in java
Zheng Da wrote:[color=blue]
> 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[/color]
I think this is a waste of your time. Java references are guaranteed
to either point to a valid object or null. There can be no wild
references. In C++ you have no such guarantee. You have no way of
knowing that an arbitrary pointer points to a valid object. In short,
if you want Java, go write Java. Now, if you want to just write a good
smart pointer, there are plenty of resources out there to help you with
that. The Boost libraries, for example, have several smart pointers
that you could use as a starting point.
[color=blue]
> templete<T>[/color]
Next time please post compilable code. We recommend copy and pasting
from your text editor instead of typing it directly.
[color=blue]
> class super_auto_ptr
> {
> class in_ptr
> {
> int ref;
> T *ptr;
> public:
> in_ptr(T *p)
> {
> ptr=p;
> ref=1;
> }[/color]
Use the initializer list for this:
in_ptr(T *p) : ref(1), ptr(p)
{
}
[color=blue]
> ~in_ptr()
> {
> delete ptr;
> }
> };
> in_ptr *ptr;
>
> struct super_auto_ptr_ref
> {
> in_ptr *ptr;
> super_auto_ptr_ref(in_ptr *p)
> {
> ptr=p;
> }[/color]
Use the initializer list here...
[color=blue]
> };
>
> public:
> //the pointer will be saved in in_ptr
> super_auto_ptr(T *p)
> {
> ptr=new in_ptr(p);
> }[/color]
....and here.
[color=blue]
> super_auto_ptr(super_auto_ptr &ref)
> {
> ptr=ref.ptr;
> ptr->ref++;
> }[/color]
You can use it for copy constructors too:
super_auto_ptr(super_auto_ptr &ref) : ptr(ref.ptr)
{
++ptr->ref;
}
[color=blue]
> ~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++;
> }[/color]
Initializer list again.
[color=blue]
> 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);
> }[/color]
operator is a reserved keyword, so it can't be a type. ITYM
'super_auto_ptr_ref operator()'.
[color=blue]
> };[/color]
Kristo |