Search code examples
c++c++11memoizationmutable

Allow const member function to edit some member variable using mutable


I want to apply the Memoization technique to increase performance of a "Line" class which was like this:

class line{
    public:
        line() = default;
        ~line() = default;

        float segment_length() const;

        Tpoint first;
        Tpoint second;
    };

As you see, the member function segment_length is marked as const because it just compute the length and does not affect the class. However, after applying the Memoization, the class line became:

class line{
    public:
        line() = default;
        ~line() = default;

        float segment_length();

        Tpoint first;
        Tpoint second;

    private:
        float norm_of_line_cashed = -1; //for optimization issue
    };

The member functionsegment_length is not const anymore becuase it is alter the norm_of_line_cashed memebnre variable.

The question:

what is the correct manner in this case:

  • Leave segment_length as non-const member function.
  • Make it const again and mark norm_of_line_cashed as mutable.

Solution

  • I would mark segment_length as const and mark norm_of_line_cashed* as mutable.

    This is following the concept of logical constness rather than bitwise or physical constness. You are only modifying internal state which won't be visible to the outside world, so logical constness is preserved even though you are technically modifying your class. This is exactly what mutable is made for and this seems like a solid design choice.

    One note: you might want to have some bool variable (or std::experimental::optional) to keep track of whether you have a value cached rather than relying on a flag values which are fragile and can lead to headaches in the future.

    *maybe you meant "cached".