我有一个看起来像这样的类:
class MyClass
{
public:
// some stuff omitted
/***
A function which, in itself, is constant and doesn't change the class
***/
void myFunction( void ) const;
private:
/***
If loaded is true, then internal resources are loaded
***/
boolean loaded;
};
Run Code Online (Sandbox Code Playgroud)
因为我这样设计了我的课,所以我不得不这样做:
MyClass :: myFunction( void ) const
{
if( !loaded )
{
// do something here
loaded = true; /** <-- this violates const **/
}
// carry out some computation
}
Run Code Online (Sandbox Code Playgroud)
因为我需要设置加载标志,所以该函数现在违反了const限定符.
我有很多代码存储常量对象,并且将它们更改为非常量将耗费时间.此外,这将有点hacky因为我真的希望对象是const.
重构我的类以保持myFunction不变的最佳方法是什么?
PS 加载保护的资源仅用于多个功能,因此提前加载它们不是一个很好的解决方案.
小智 11
使用mutable关键字.
class MyClass
{
public:
void myFunction( void ) const;
private:
mutable boolean loaded;
};
Run Code Online (Sandbox Code Playgroud)
这表示加载的成员应该被视为逻辑上的const,但物理上它可能会改变.