In RAII, resources are not initialized until they are accessed. However, many access methods are declared constant. I need to call a mutable
(non-const) function to initialize a data member.
Example: Loading from a data base
struct MyClass
{
int get_value(void) const;
private:
void load_from_database(void); // Loads the data member from database.
int m_value;
};
int
MyClass ::
get_value(void) const
{
static bool value_initialized(false);
if (!value_initialized)
{
// The compiler complains about this call because
// the method is non-const and called from a const
// method.
load_from_database();
}
return m_value;
}
My primitive solution is to declare the data member as mutable
. I would rather not do this, because it suggests that other methods can change the member.
How would I cast the load_from_database()
statement to get rid of the compiler errors?