Search code examples
c++pointersthisconst-cast

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


Solution

  • this is not an l-value.

    You cannot assign it to point to something else.

    You can do *this = *obj; which does not require a const_cast

    You can do a const_cast<A*>(this) to override constness, and as with any other const_cast is fraught with danger, but it would enable you to perform a const/non-const overload without having to duplicate the implementation e.g.

    T& A::get()
    {
     // some complex code to find the right reference, assigning to t
      return t;
    }
    
    const T& A::get() const
    {
    // implement in terms of above function
      return (const_cast<A*>(this))->get(); // invokes above
     // and automatically converts the reference to const
    }