非const复制构造函数

时间:2015-06-15 11:20:59

标签: c++ constructor const copy-constructor observers

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

在更改我们的对象之前,我们需要通知其他人,以便他们可以执行真正的应对。对于这个动作,我决定使用观察者模式:

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

然后,我们的对象继承它们。问题是,在copy-constructor中,当我们得到const参数时,我们需要调用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,但我认为它不适合那里,因为对象在逻辑上已经改变。

还有其他想法吗?

1 个答案:

答案 0 :(得分:2)

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

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