lundi 30 novembre 2015

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.

Aucun commentaire:

Enregistrer un commentaire