c++ - Avoiding code duplication (const-correctness) redux -


I was reading it about cons - accuracy here. Scott Meyer's solution seems to be around a good job, but what if you have a member's function (which requires both the console and non-current version) which is this indicator If the member is a function then const then it automatically compresses , which is a single const Function where the bulk code is false

One potential task- one such work around me That was done as a code to pass the context of this to the const function, so the function can use that context instead of directly using it Indicator but, is it safe? It seems that if you are not actually using const_cast on any const-object instead, you can only do so by the const member function A non-constant reference of the object is canceling the contract.

For example:

  square fu {private: template  

It seems that a great amount of code is a good way to avoid duplicating code, when a const and non-const version of a function is required, but is it safe ? Or can it somehow cause undefined behavior?

Note that even if you const constitute f1) and you " ", Modify f2 () , is marked as non-contact, thus can be modified by calling f2 () item . And f1 () alone will not allow you to modify "this" (or any const object) in your own way f2 () const foo < / Code> can not call with the help of the object, so it does not bring any benefit.

In other words - In your example, non-const f1 () will be sufficient if you do not need f1 () const or both versions.


UPDATE You will no longer be able to modify v1 () in the "const" version of itself is called zero f1 (const foo and self) by const .


Comments