class SomeClass {
public:
void Render() const;
private:
mutable Cache m_some_cache;
};
Is the class above const-correct? When can I safely say “This operation doesn’t change the internal state of an instance”?
In the above example SomeClass is something that renders stuff on the screen. It uses a cache (for example OpenGL buffer objects) to allow faster processing for further calls. So the only thing that changes internally is the cache object. I’m asking myself if a cache already belongs to an internal state of a renderer.
The example is very minimal, but in my real application this goes down a road with many classes, i.e. a lot of Render() calls are involved, and most of them do caching only. But some do also load resources through a resource loader — is the assumption here still right that a method may be const even if it queries a resource manager for loading a resource?
Think of it this way. This is perfectly valid:
You aren’t modifying the object itself, so the use of the
constqualifier is perfectly valid. This method is modifyingstd::cout, but that doesn’t count as far as theconstness ofType::print_self()goes.That said,
mutable Cachelooks to me to be a contradiction in terms unless you are only using thatCacheelement for local storage withinRender. If you are truly using it as a cache it seems a bit dubious to qualify this element asmutable. Use it as a cache (e.g., across calls toRenderrather than within a call toRender) and you have lied to both the compiler and to the user of the class.Edit
Per the comments made by the OP, the
Rendermethod truly is the graphical equivalent ofprint_self(). The ‘real’ state of the object (presumably not shown for the sake of constructing a minimal working example) presumably isn’t modified by rendering. DesignatingRenderas aconstmethod is the right thing to do. If theCachedata member reason for being is to serve as speed bump that avoids the cost of constructing and destructing it with each call toRenderthere is nothing wrong with qualifying thatCachemember asmutable(which is needed so thatRendercan remainconst).