简体   繁体   English

非常量复制构造函数

[英]Non-const copy constructor

I'm doing copy on write optimization for object (ie 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:问题是,在复制构造函数中,当我们获取 const 参数时,我们需要调用 register_observer,这是非常量方法:

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.我发现的一种可能的解决方案是使用mutable ,但我认为它不适合那里,因为 object 在逻辑上发生了变化。

Any other ideas?还有其他想法吗?

In your case, you probably should use the mutable keyword.在您的情况下,您可能应该使用mutable关键字。

Your object would still remain logically const because, from the user point of view, nothing has changed.您的对象在逻辑上仍将保持不变,因为从用户的角度来看,没有任何变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM