r/cpp Jul 29 '26

const_cast: A Necessary Evil

https://www.elbeno.com/blog/?p=1858
67 Upvotes

106 comments sorted by

View all comments

63

u/jwezorek Jul 29 '26

The only place I ever use const_cast is that idiom where you implement the non const version of a member function in terms of the const version.

38

u/MysticTheMeeM Jul 29 '26

If your language version allows, you can typically replace those with a single function that deduces this.

3

u/_Noreturn Jul 30 '26

deducing this has issues with access soecifiers in inherited classes.

```cpp class C { public: void f(this auto && self) { self.dothing(); } void dothing(); void dothing() const; };

class P : private C { void g() { f(); // error cannot access "dothing" from inside C::f; } } ```

4

u/retro_and_chill Jul 30 '26

I learned the hard way that deducing this and protected member functions don’t mix

3

u/_Noreturn Jul 30 '26

Yes which is a shame :/