非常量复制构造函数

Non-const copy constructor

我正在对对象进行写时复制优化(即,当调用复制构造函数时,只需保存指向对象的指针并仅在我们需要更改对象或我们指向的对象时才真正复制它改变)。

在改变我们的对象之前,我们需要通知其他人,这样他们才能进行真正的应对。对于此操作,我决定使用观察者模式:

struct subject {
    void register_observer(const event& e, observer& obs);
    void notify(const event& e) const;

private:
    std::map<event, std::vector<observer*> > _observers;
};

观察员:

struct observer {
    virtual void onEvent(event e);
};

那么,我们的对象继承了他们两个。问题是,在复制构造函数中,我们需要调用 register_observer,这是非常量方法,当我们得到 const 参数时:

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);
    }
}

我发现的一个可能的解决方案是使用 mutable,但我认为它不适合那里,因为对象在逻辑上发生了变化。

还有其他想法吗?

在您的情况下,您可能应该使用 mutable 关键字。

您的对象在逻辑上仍将保持为 const,因为从用户的角度来看,没有任何变化。