简体   繁体   中英

How to refactor a class in C++ to make a certain function const?

I have a class which looks something like this:

class MyClass
{
public:
  // some stuff omitted

  /*** 
    A function which, in itself, is constant and doesn't change the class
  ***/
  void myFunction( void ) const;
private:
  /***
    If loaded is true, then internal resources are loaded
  ***/
  boolean loaded;
};

Because I designed my class this way I am forced to do this:

MyClass :: myFunction( void ) const
{
  if( !loaded )
  {
     // do something here

     loaded = true; /** <-- this violates const **/
  }

  // carry out some computation
}

Because I need to set loaded flag the function now violates const qualifier.

I have a lot of code that stores constant objects and it will be time consuming to go round and change them to non-const. Moreover, this will be slightly hacky since I really want the objects to be const.

What is the best way to refactor my class in order to keep myFunction constant?

PS The resources guarded by loaded are required only for several functions and therefore loading them in advance is not a very good solution.

Use the mutable keyword.

class MyClass
{
public:
  void myFunction( void ) const;
private:
  mutable boolean loaded;
};

This says that the loaded member should be treated as being logically const but that physically it may change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM