简体   繁体   English

“ this”指针上的const_cast是未定义的行为吗?

[英]Is const_cast on “this” pointer an undefined behavior?

I have got the following c++ code. 我有以下c ++代码。 I can compile it with g++ 4.9.2 on Linux machine. 我可以在Linux机器上使用g ++ 4.9.2进行编译。 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. 然后,当我运行它时,它会显示10。似乎在默认构造函数中创建了一个新对象并将其分配给使用const_cast创建的指针。 There are no memory leaks (which I checked using valgrind). 没有内存泄漏(我使用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;
}

const_cast has nothing to do with the behavior you experience. const_cast与您遇到的行为无关。 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. 前构造体存储器的对象this被保留。
  2. x(0) 0 is assigned to the member x of this . x(0) 0分配给this的成员x
  3. A(10) A new (unnamed) object of class A is created using the constructor A(int) . A(10)类的新(未命名)对象A使用构造创建A(int) This new object member x has value 10 . 这个新的对象成员x值为10
  4. this= Here the unnamed object is assigned (using the automatically generated copy assignment operator, which is field-wise) to *this . this =这里,未命名的对象(使用自动生成的副本分配运算符,按字段方式)分配给*this Thus, value of member x of this becames 10 . 因此,部件的值xthis becames 10
  5. after that line The temporary unnamed object is destroyed. 在该行之后临时的未命名对象被破坏。
  6. this is returned. this被返回。

This is perfectly legal and expected behavior. 这是完全合法和预期的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM