How can you assign a value to the pointer 'this' in C++

后端 未结 6 2173
北荒
北荒 2020-12-08 21:03

In a function, how to you assign this a new value?

6条回答
  •  佛祖请我去吃肉
    2020-12-08 21:54

    You can't.

    9.3.2 The this pointer [class.this]

    1 In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. [...] (emphasis & link mine)

    You can modify the object this points to, which is *this. For example:

    struct X
    {
       int x;
       void foo()
       {
         this->x =3;
       }
    };
    

    The method modifies the object itself, but something like this = new X is illegal.

提交回复
热议问题