RAII: initializing a data item in const mode

In RAII, resources are not initialized until they are available. However, many access methods are declared persistent. I need to call a function mutable(not const) to initialize a data item.

Example: booting from a database

struct MyClass
{
  int get_value(void) const;

  private:
     void  load_from_database(void); // Loads the data member from database.

     int m_value;
};

int
MyClass ::
get_value(void) const
{
  static bool value_initialized(false);
  if (!value_initialized)
  {
    // The compiler complains about this call because
    // the method is non-const and called from a const
    // method.
    load_from_database();
  }
  return m_value;
}

My primitive solution is to declare the data item as mutable. I would prefer not to do this because it assumes that other methods can modify a member.

How can I get the operator to load_from_database()get rid of compiler errors?

+3
source share
6 answers

RAII. RAII , .

, Lazy. .

mutable, .

, const_cast, , - :

static const MyClass Examplar;

, ? , const_cast undefined. .

const_cast, R Samuel Klatchko do.

, , . , : get, set load_from_database, , mutable.

+20

. , , .

+5

, , , ( ) RAII. , , const mutable . const mutable .

, , , , - . ++ ( ), - , (, , ) . (.. -, ).

( ) MyClass, , - , . : 1) MyClass - lazy_int 2) ( , ) get_value(), , operator int(). , m_value, , , , , .

. int ( ) operator int(), , .

+5

[ ! !:))]

struct DBValue 
{
  int get_value();

private:
  void load_from_database();
  int value;
};

struct MyClass 
{
  MyClass(): db_value(new DBValue()) {}
  ~MyClass() { delete db_value; } 

  int get_value() const;

private:
  DBValue * const db_value;
};

int MyClass::get_value() const
{
  return db_value->get_value(); // calls void load_from_database() if needed
}

, MyClass const , , const non const const .

+4

const_cast, . mutable , , , , , , , .

+1

If your method changes the state of the object (for example, changing the state of the base database), then the method should not be const. In this case, you must have a separate, non-constant loadmethod, which must be called before the call const.

This method requires neither const_castnot mutable, and will make a potentially expensive operation explicit.

0
source

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


All Articles