Allow const member function to edit some member variable using mutable

I want to apply the Memoization method to improve the performance of the Line class, which was something like this:

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

        float segment_length() const;

        Tpoint first;
        Tpoint second;
    };

As you can see, the member function is segment_lengthmarked as constbecause it simply calculates the length and does not affect the class. However, after applying 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
    };

A member function is segment_lengthno longer a constant because it modifies the membnre variable norm_of_line_cashed.

Question:

which is correct in this case:

  • Leave segment_lengthas a member function non-const.
  • Do it constagain and mark norm_of_line_cashedhow mutable.
+4
1

segment_length const norm_of_line_cashed * mutable.

, . , , , . , mutable, .

: bool ( std::experimental::optional), , , , .

* , "".

+4

Source: https://habr.com/ru/post/1617950/


All Articles