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

删除回忆录丶 提交于 2019-12-08 23:10:58

问题


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


回答1:


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.




回答2:


You can assign the object this points at:

*this = XY;

But you can't assign the direct value of this:

this = &XY;   // Error: Expression is not assignable



回答3:


Long ago, before the first C++ standard has been published, some compiler implementations allowed you to write the following code inside a constructor:

this = malloc(sizeof(MyClass)); // <<== No longer allowed

The technique served as the only way to control allocation of class of objects. This practice has been prohibited by the standard, because overloading of the operator new has solved the problem that used to be tackled by assignments to this.




回答4:


You can't. If you feel the need to do this perhaps you should be writing a static method taking a class pointer as it's first parameter.




回答5:


You cannot assign value to this pointer. If you try to assign the value to the this somthing like this = &a it would result in illegal expression




回答6:


You can not. "this" is a hidden argument to every member function of a class and its type for an object of Class X is X* const. This clearly means that you can not assign a new vale to "this" as it is defined as a const. You can however modify the value pointed to by this. Refer http://www.geeksforgeeks.org/this-pointer-in-c/ for more details.



来源:https://stackoverflow.com/questions/13476879/how-can-you-assign-a-value-to-the-pointer-this-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!