Change 'this' pointer of an object to point different object

后端 未结 6 1452
花落未央
花落未央 2021-02-07 08:01
class C{
   //methods and properties
}

void C::some_method(C* b){
    delete this;
    this = b;     
}

This gives me follwing error when compiling:

6条回答
  •  清歌不尽
    2021-02-07 08:49

    The this-pointer is an implicit pointer to the object in whose context you are working, you cannot reassign it.

    According to Stroustrup's bible (The C++ Programming Language, 3rd edition I have) this is expressed as

    C * const this
    

    meaning you have a constant pointer to your class C, so the compiler will complain if you try to change it.

    EDIT:

    As I was corrected, the above mentioned expression does not describe this fully correctly, for this is actually an rvalue.

提交回复
热议问题