c++ - a class design problem -


In the book "C + Programming Language", the author has given the following example: "Before using the cache, Need to fill ". I think this is the reason that the function of compute_cache_value has been kept. But I do not understand what implementations of string_rep () do according to its implementation. Thank you for clarification. class date {bool cache_valid; String cache; Zero compute_cache_value (); // fill cache // ... public: // ... string string_rep () const; }; String date :: string_rep () const {if (cache_valid == incorrect) {date * th = console-type & lt; Date & date; (this); // remove cast const-> compute_cache_value (); Th-> cache_valid = true; } Return cash; }

Additionally, the author gave the following for example:

  date d1; Call date d2; String s1 = d1.string_rep (); String s2 = d2.string_rep ();   

And the author said that the fourth example will display undefined behavior. I would like to know why class = "text">

string_rep checks if there is no cache string representing date , Then it calls the compute_cache_value method to represent the string and cache it, and then marks the cache presentation, because in the future the string_rep Should not be calculated.

line const date d2; will display undefined behavior because the compiler can assume that it can insert d2 in nonvolatile memory (for example, flash, or read-only memory or memory-mapped in a microcontroller To read the memory), and const_cast & lt; Date * & gt; can not work in that case, resulting in cache_valid staying incorrect or cache as a blank string .

As in the case of this example, using const_cast , below, Michael J is given below, in this example, shaky The keyword comes in hand. In short, by marking a unselected member to a member of the class, the object can be changed, even if the object const

  class date {mutual bridge cache_widies; Unstable string cache; Zero compute_cache_value () console; // ... public: // ... string string_rep () const; }; String date: string_rep () const {if (cache_valid == incorrect) {compute_cache_value (); Cache_valid = true; } Return cash; }   

... though I think it is the responsibility of setting compute_cache_value to cache_valid , and I consider adding operator string () const {return string_rep (); } to date .

One last thing that is clear about instability is that what is the better practice of compiler, const

Comments