J
Jim Campbell
Suppose I wanted to a class to contain a pointer, but I didn't want to
make the copy constructor or assignment operator reinitialize this
pointer. (Think of a class that contains an mmapped pointer - having to
duplicate the memory could be very expensive.) Instead, I wanted only
the non-copy construction to create the pointer, and have copies of the
object, achieved through either copy construction or assignment, refer
to the pointer through a reference; in other words, "proxy" the original
object. If an original object changes its pointer, all copy constructed
or reassigned objects will see the update with minimal overhead.
I developed this simple class below to demonstrate how this could be done:
class PtrClass
{
public:
PtrClass(char *p = NULL) : ptr_(p), cpref_(ptr_) { }
PtrClass(const PtrClass &co) : ptr_(NULL), cpref_(co.cpref_) { }
PtrClass &
operator =(const PtrClass &rhs)
{
if (this != &rhs)
{
memcpy(this, &rhs, sizeof(*this));
ptr_ = NULL;
}
return *this;
}
char *getPtr() const { return cpref_; }
~PtrClass() { ptr_ = NULL; }
private:
char *ptr_;
char * &cpref_;
};
My question now: Is there any way within the C++ language to implement
the assignment operator so that the reference is carried from the right
hand side to the destination? Since references can never be reassigned,
the only way I can see around it is by going around C++'s back with the
memcpy().
Thanks,
Jim
make the copy constructor or assignment operator reinitialize this
pointer. (Think of a class that contains an mmapped pointer - having to
duplicate the memory could be very expensive.) Instead, I wanted only
the non-copy construction to create the pointer, and have copies of the
object, achieved through either copy construction or assignment, refer
to the pointer through a reference; in other words, "proxy" the original
object. If an original object changes its pointer, all copy constructed
or reassigned objects will see the update with minimal overhead.
I developed this simple class below to demonstrate how this could be done:
class PtrClass
{
public:
PtrClass(char *p = NULL) : ptr_(p), cpref_(ptr_) { }
PtrClass(const PtrClass &co) : ptr_(NULL), cpref_(co.cpref_) { }
PtrClass &
operator =(const PtrClass &rhs)
{
if (this != &rhs)
{
memcpy(this, &rhs, sizeof(*this));
ptr_ = NULL;
}
return *this;
}
char *getPtr() const { return cpref_; }
~PtrClass() { ptr_ = NULL; }
private:
char *ptr_;
char * &cpref_;
};
My question now: Is there any way within the C++ language to implement
the assignment operator so that the reference is carried from the right
hand side to the destination? Since references can never be reassigned,
the only way I can see around it is by going around C++'s back with the
memcpy().
Thanks,
Jim