Search code examples
c++thisundefined-behaviorconst-cast

Is const_cast on "this" pointer an undefined behavior?


I have got the following c++ code. I can compile it with g++ 4.9.2 on Linux machine. Then when I run it, it prints 10. It seems that a new object is created and assigned to the pointer created using const_cast in the default constructor. There are no memory leaks (which I checked using valgrind). Is this some kind of an undefined behavior or is it legal?

#include <iostream>

using namespace std;

class A
{
   public:
      A() : x(0)
      {
         A *tmp = const_cast<A*>(this);
         *tmp = A(10);
      }

      A(int x)
      {
         this->x = x;
      }

      int getX() const
      {
         return x;
      }

   private:
      int x;
};

int main()
{
   A a;

   cout << a.getX() << endl;

   return 0;
}

Solution

  • const_cast has nothing to do with the behavior you experience. Your code may be simplified to the following:

      A() : x(0)
      {
         *this = A(10);
      }
    

    So, here the following happens if we want to create an object using a default constructor:

    1. before constructor body Memory for the object this is reserved.
    2. x(0) 0 is assigned to the member x of this.
    3. A(10) A new (unnamed) object of class A is created using the constructor A(int). This new object member x has value 10.
    4. this= Here the unnamed object is assigned (using the automatically generated copy assignment operator, which is field-wise) to *this. Thus, value of member x of this becames 10.
    5. after that line The temporary unnamed object is destroyed.
    6. this is returned.

    This is perfectly legal and expected behavior.