0

I found two questions on stack overflow related to const_cast:

1) How do I remove code duplication between similar const and non-const member functions?

2) Is this undefined behavior with const_cast?

Let say we want to avoid code duplication like in answer for question 1:

struct C
{
  const char& get() const
  {
    return c;
  }
  char& get()
  {
    return const_cast<char&>(static_cast<const C&>(*this).get());
  }
  char c;
};

Let's use that class like that:

C obj;
obj.get() = 'a';

As I see we cast away a constness of c inside getter function and assign to its new value, so according to the second question, we should get undefined behavior.

Why assigning to c is not an undefined behavior?

akulinich
  • 55
  • 1
  • 5
  • 1
    Keep in mind that in the non-`const` overrload of `get` you know for a fact that `this` refers to a non-`const` instance of `C`. – François Andrieux Mar 18 '19 at 17:04
  • But standard says that we can't modify objects after const_cast. (First answer of the [question](https://stackoverflow.com/questions/25406818/is-the-following-use-of-const-cast-undefined-behavior)) – akulinich Mar 18 '19 at 17:10
  • 1
    You can't modify a `const` object after `const_cast`. You certainly can if it isn't actually `const`. In the question you linked the `const int` is *actually* `const`. In your case you have a `const` reference to an actually non-`const` instance. – François Andrieux Mar 18 '19 at 17:11
  • Do we have that in the standard? – akulinich Mar 18 '19 at 17:12
  • The standard's section on [cv-qualifiers](https://timsong-cpp.github.io/cppwp/dcl.type.cv) (`const` and `volatile` qualifiers) has an example of a valid and of an invalid attempt at modifying a value through a `const_cast`. – François Andrieux Mar 18 '19 at 17:14
  • Any code containing `const_cast` should *not* pass code review unless it comes with 10 times more comments explaining why than actual code. – Jesper Juhl Mar 18 '19 at 18:03
  • @JesperJuhl: True. But this is a very common pattern and will easily pass code review because it is a well known (and understood) common pattern. – Martin York Mar 18 '19 at 18:16
  • This is perfectly fine. You are not modifying a const object. You simply have a const reference to a non-const object (which is also fine). Since you know (inside the non-cost get()) that your object is not const it is fine to cast away the const as it can't lead to UB. – Martin York Mar 18 '19 at 18:18

1 Answers1

2

It is UB to modify a const object.

  • obj is not declared const.
  • static_cast<const C&>(*this) is "just" an alias.

So you are fine here.

Jarod42
  • 173,454
  • 13
  • 146
  • 250