Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying const_cast on this-> pointer

I was playing with some code to remove constant-ness of variable.

  int *i = new int(202);
  int *j = new int(402);

  int *const iptr = i;    // Constant pointer
  //iptr = j ;           // Not allowed. Constant pointer cannot point to another location.
  (*iptr)++;             // Allowed
  const_cast<int *>(iptr) = j;
  cout<< *iptr           // prints 402

It works as expected but when I try to remove constantness of "this" pointer, Compiler doesnt allow it, i.e. it shows squiggling lines underneath the const_cast statement.

class A
{
public:
  A(A * obj)
  {
    const_cast<A *>(this) = obj; 
  }
};

When I hovered mouse (I am using VS2014) over "this" and "iptr" from earlier code, I could see the type is same i.e. <classname> *const

Can anybody please explain what is going on under the hood?

Cheers,

Saket

like image 654
sacket Avatar asked Mar 04 '26 16:03

sacket


1 Answers

I am afraid you did not understand what const_cast is for.

In C++, const is used in two instances:

  • a const object logical value cannot be changed (and, barring mutable fields, its bitwise value cannot be changed either)
  • const* or const& are read-only pointers or references

const_cast is not about changing const objects, it's about modifying non-const objects through read-only pointers or references

Bear in mind though that shooting yourself in the foot is easy, because when you get a const& how do you know whether the original object is const or not ? You do not. And if you attempt to change one that is const, a unicorn appears, or maybe the devil (also know as Undefined Behavior: anything may happen).

Now, the correlation with this is tricky. Strictly speaking this is an r-value (meaning it can only appear as-is on the R ight-hand side of =), though it is often described as simply being const for simplicity's sake, so in a constructor of A this is described as having type A* const. Thankfully for us, even in this approximation const_cast is a bad idea since the original object is const.


Therefore, the recommendation is:

  • Junior: Do not use const_cast, reinterpret_cast or C-style casts (because it is not obvious when they desugar to one of the first two).
  • Senior: You are not experienced enough.
  • Expert: Come on! How can you claim you are an expert and attempt to use them ?
like image 90
Matthieu M. Avatar answered Mar 06 '26 05:03

Matthieu M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!