I'm doing copy on write optimization for object (i.e. when calling a copy-constructor just save pointer to an object and really copy it only if we need to change our object, or if object we are pointing to going to change).
Before changing our object we need to notify others about it, so they can perform real coping. For this action I decided to use observer pattern:
struct subject {
void register_observer(const event& e, observer& obs);
void notify(const event& e) const;
private:
std::map<event, std::vector<observer*> > _observers;
};
and for observers:
struct observer {
virtual void onEvent(event e);
};
then, our object inherits both of them. The problem is, that in copy-constructor, we need to call register_observer, which is non-const method, when we get const argument:
my_class::my_class(my_class const &other) {
if (other._copy != NULL) this->_copy = &other;
else {
this->_copy = other._copy;
this->_copy->register_observer(event::CHANGED, *this);
}
}
One possible solution I've discovered is to use mutable
, but I think it doesn't fit there, because object is logically changed.
Any other ideas?
In your case, you probably should use the
mutable
keyword.Your object would still remain logically const because, from the user point of view, nothing has changed.