C ++:可变,创造巨大的内部变化

时间:2015-07-14 09:07:45

标签: c++ const mutable const-correctness

这是事情: 我有一个类可以以两种方式存储一些数据,也就是说,在两个表示相同数据的对象中,small_type和big_type。 small_type是内存效率高但访问时间不好,big_type则相反。 big_type仅根据需要从small_type创建。 创建big_type的方法需要很长时间,因此我们希望在类中存储big_type,假设所有方法都保证两个变量的一致性。 据我所知,const的正确性如下:

class MyClass {
public:

    (some constructors et cetera)

    SmallType get_small_type() const{
        return small_type;
    }

    BigType get_big_type() const{
        if(!big_type_created){
            create_big_type(); //will set big_type_created to true
        }
        return big_type;
    }

private:
    SmallType small_type;
    mutable BigType big_type;
    mutable bool big_type_created; //default false
    void create_big_type() const;
}

首先,由于我是初学者,这是否符合const正确性? 这是我的代码问题:create_big_type()需要时间,很多时间(可能需要几分钟)。从外面可以清楚地看到这一次。因此,虽然逻辑状态没有改变,但从外部可以清楚地看到事情发生了。还是对吗?

另一个问题是,如果有更改small_type的setter并设置一些boolean big_type_dirty为true会导致big_type再次被要求重新创建吗?

0 个答案:

没有答案