Topic: Q: Overload operator-> on "const"ness of method
Author: kvilekva@nic.cerf.net (Kristian Kvilekval)
Date: 12 Jul 1994 18:50:53 GMT Raw View
I am working on making some classes that working through a handle class.
The class to be handled will be a reference counted copy-on-write
very similar to many string class implementations.
struct object
{
unsigned count;
void m1 () const; // do not modify object.
void m2 (); // Modify object.
object* clone (); // make a copy.
};
Notice the two methods (m1,m2). One changes the underlying representation
the other does not. This matters when two handles point to the same object,
because as long as no method modifies the object I can have any number
of handles point to the same representation.
Below is s smart pointer class. I would like to overload the operator->
to tell when a method will modify the underlying object and when it will
not. This information is contained in the `const'ness of each method.
Anybody know what the standard is doing about overloading the operator->
on the second parameter.
class handle
{
object* ptr_;
public:
const object* operator-> () const { return ptr_; }
object * operator -> ()
{
copy_on_write ();
return ptr_;
}
void copy_on_write ()
{
if (ptr_->count>1) ptr_= ptr->clone();
return ptr_;
}
handle () { ptr_ = new object; }
~handle () { delete ptr_; }
};
fun()
{
handle p;
p->m1 (); // call the method that will *not* clone
p->m2 (); // m2 will modify thge object co may need to clone.
}
Author: jason@cygnus.com (Jason Merrill)
Date: Wed, 13 Jul 1994 02:50:07 GMT Raw View
>>>>> Kristian Kvilekval <kvilekva@nic.cerf.net> writes:
> Anybody know what the standard is doing about overloading the operator->
> on the second parameter.
You cannot overload methods on the basis of return type. I would suggest
using accessor methods to modify the object pointed to; that way it
becomes trivial to determine when you need to make a copy.
Jason