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?
This is not RAII. In RAII you would initialize it in the constructor, which would solve your problems.
So, what you are using here is
Lazy. Be it lazy initialization or lazy computation.If you don’t use
mutable, you are in for a world of hurt.Of course you could use a
const_cast, but what if someone does:And the compiler decides it is a good candidate for Read-Only memory ? Well, in this case the effects of the
const_castare undefined. At best, nothing happens.If you still wish to pursue the
const_castroute, do it asR Samuel Klatchkodo.If you thought over and think there is likely a better alternative, you can decide to wrap your variable. If it was in class of its own, with only 3 methods:
get,setandload_from_database, then you would not worry about it beingmutable.