Advertisement
193030

03. Logic constness (mutable

Jul 8th, 2021
867
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6.  // If the logic const is the goal, use mutable members to implement
  7.  
  8. class BigArray
  9. {
  10.     vector<int> v;
  11.     //mutable int   accessCounter; // first way.
  12.     int accessCounter;
  13.  
  14. public:
  15.     int getItem(int index) const
  16.     {
  17.         //accessCounter++; // first way
  18.         const_cast<BigArray*>(this)->accessCounter++; // Note: The casting is hacking way of coding, use it only when it had to.
  19.         return v[index];
  20.     }
  21. };
  22.  
  23.  
  24. int main()
  25. {
  26.     // 1. The first way to change variable in const function is to declare the variable with the keyword mutable.
  27.     // 2. The second is to cast the variable
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement