Is the corresponding C ++ mutable in this case?

I would like to ask if using mutable is appropriate:

#include <iostream>

class Base
{
protected:
  int x;

public:
  virtual void NoMod() const
  {
    std::cout << x << std::endl;
  }
  void Draw() const
  {
    this->NoMod();  
  }
};

class Derive : public Base
{
private:
  mutable int y;

public:
  void NoMod() const
  {
    y = 5;
  }
};

int main()
{
  Derive derive;

  // Test virtual with derive
  derive.Draw();

  return 0;
}

The base class is a third-party library. I am expanding it to provide my own NoMod (). The original NoMod () library is declared as const.

My NoMod () differs from Base in that it needs to change its own member variable.

So for my own NoMod () to compile and call the call when Draw () is called, I had to

1) Implement Derive :: NoMod () as const 2) make my int y mutable.

Is this the best I can do?

+3
source share
7 answers

As described in the geek chapter, the answer to your question depends on how your data member is used.

.

"" "" . .

, "" , " /", . , , . .

, , , . , . , , , . , . . booean data, , , , "" .

, const, . , , , , , , ( , ). , . , const, .

, , , , , , .

+8

, - , y .

mutable , "" . , C, mLength, , , const. , mutable .

+9

, , mutable , , , .

y , , , .

+3

, "", - - "const", (=), 'const'.

, const_cast apllied 'const' U.B. ++. , "const", , "" .

, ! .

,

+1

mutable, (, /, ).

. const . const_cast:

const_cast< Derive*>( this)->y = 10;

const_cast, , , const, , .

, , , , mutable .

+1

, , :

  • . , Rectangle, - GetSurface(), , , , - m_surfaceCache, .
  • . , CriticalSection:: Enter() const, , .

, , mutable , ++.

+1

, , , . ++ - , , " ".

, , , NoMod , const. , . NoMod , , const .

, .

+1

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


All Articles