Leveraging const-correctness
As we saw in Chapter 1, Core Tasks, D's const
and immutable
methods provide strong guarantees. Sometimes, these strong guarantees make them difficult to use. Here, we'll look at how to make the most of const
without letting it get in our way.
Getting ready
First, let's create a class to demonstrate the problem as shown in the following code:
class CachingObject { private int cache; private bool cacheSet; int getExpensiveComputation() { if(!cacheSet) cache = 31415927; // suppose this was an expensive calculation… return cache; } }
We can use this method without trouble by simply passing the object around as a mutable instance. However, what happens if we want or have to use const
? For example, while implementing the toString
method, this is forced to be const
by the base class signature as shown in the following code:
override string toString() { … } // compile error, it must be const override string toString() const { // this signature works… ...