Class design problem

In the book "C ++ Programming Language" the author gave the following example. He mentioned that "the cache needs to be filled before it can be used." It seems to me that this is why the compute_cache_value function is posted. But I don’t understand what the string_rep () function does according to its implementation. Thanks for clarifying.

class Date{
      bool cache_valid;
      string cache;
      void compute_cache_value( );  //fill cache
      // ...
public: 
      // ...
     string string_rep( ) const;
};

string Date:: string_rep( ) const
{
    if (cache_valid == false) {
          Date* th = const_cast<Date*> (this); // cast away const
          th->compute_cache_value( );
          th->cache_valid = true;
    }
    return cache;
}

In addition, the author gave the following examples:

Date d1;
const Date d2;
string s1 = d1.string_rep( );
string s2 = d2.string_rep( );

And the author stated that the fourth example will display undefined behavior. I would like to know why.

+3
source share
4 answers

string_rep , . , compute_cache_value , , string_rep .

const Date d2; undefined, , d2 (, - ) const_cast<Date*> , cache_valid false cache .

P.S. . , -, const_cast. mutable. , mutable , , const.

class Date
{
      mutable bool cache_valid;
      mutable string cache;
      void compute_cache_value() const;
      // ...
public: 
      // ...
     string string_rep() const;
};

string Date::string_rep() const
{
    if (cache_valid == false) {
          compute_cache_value();
          cache_valid = true;
    }
    return cache;
}

... , compute_cache_value cache_valid, operator string() const { return string_rep(); } Date.

, mutable, , , , , d2, , const.

+5

string_rep() . undefined 4 - d2 const. const_cast ( ) const'ness.

+1

string_rep "const". , . , const_cast(), .

, , , , , .

d2, d2 - const. , " ".

, ?

  • . , .
  • , .
  • , .
  • This can trick the optimizer into doing something crazy, and then all bets are off. At this point, almost anything can happen.

Bottom line: this is unnecessary and stupid. Do not do that. There are almost always better ways than dropping a constant.

0
source

All Articles