A graph can be represented as either an adjacency matrix or an adjacency list. My Graph
object represents the graph as an adjacency matrix. For performance reasons, I don't calculate the adjacency list unless it is requested; however, once requested, I would like to retain the list (to avoid re-building it).
Is it appropriate to make the adjacency list mutable
, so that users can generate the adjacency list for otherwise const
Graph
objects? I ask because I'm not convinced that building the adjacency matrix would be considered a "physical" as opposed to "logical" change to the state of the Graph
. I also have an adjacencyListBuilt
method, so the building of the adjacency list isn't "invisible" (see https://isocpp.org/wiki/faq/const-correctness#mutable-data-members).
If I understand correctly, declaring the adjacencyList
instance variable mutable
will allow any method to update it. Is there a way whereby only the buildAdjacencyList
method is able to modify the adjacencyList
instance variable on a const
object?
Caching the results calculated from internal members using
mutable
is appropriate. Be aware that it can break the thread safety.But I would also consider a separate class or function that performs a computation on a
const
object.