I have a factory class that will be used to create a whole lot of instances of a certain class. The creation process is pretty obfuscated and might require a quite a while. So I was thinking it would be smart to store the instances of the class which have already been created inside the factory, I can recall them at a later time.
The creation depends on a single parameter (the name) so things can be stored in a std::map which I call old_instances.
A A_factory::make_A(std::string const& name)
{
if ( old_instances.find(name) != old_instances.end() )
{
return old_instances.find(name) -> second;
}
else
{
// obfuscated creation process that creates instance 'new_A'
// ...
old_instances.insert(std::pair<std::string, A>(name, new_A)); // <- problem
return new_A;
}
}
The problem here is that this whole routine could be a const member of the factory. But because the old_instances is adapted.
I kinda feel awkward sacrificing the const-ness of a function for something this trivial.
Are these kind of sacrifices logical?
please do not shoot me if this question is too dependent on taste.
This is the classic example of using
mutable. You should be fine doing this as long as the external behavior truly is that of const.