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

后端 未结 6 1385
花落未央
花落未央 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:37

    Just use the usual approach instead of black magic and UB:

    C* c1 = new C();
    C* c2 = new C();
    
    // do some work perhaps ...
    
    delete c1;
    c1 = c2;
    

    Now c1 is an alias to c2 as you wanted. Be careful though when cleaning up memory so you don't end up deleting an object twice. You might perhaps consider smart pointers...

    0 讨论(0)
  • 2021-02-07 08:47

    The error says "You can't assign b to this". As far as I know, this is something you can't change, because it's not an actual pointer, but a self-reference.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-07 08:50

    You can't assign a different value to this as it point to the object itself, and this haven't any sense. You could instantiate a new object and use its implicit this pointer instead.

    Moreover, if you try to make a copy of object, you can overwrite operator=

    class Foo
    {
      public:
        [...]
        Foo& operator=(const Foo& foo);
    }
    
    int main()
    {
     Foo foo;
     foobar = foo; //invoke operator= overwrited method
    }
    


    0 讨论(0)
  • 2021-02-07 08:53

    You cannot change what this points to. I would also not know why you'd want to do this.

    0 讨论(0)
  • 2021-02-07 08:59

    To quote the standard:

    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.

    A "prvalue" is a pure rvalue, something like 42 or 3.14159. In the same way you can't do something like 42 = x, you can't assign to this; in both cases (at least conceptually), there is no object whose value can change.

    And I'm really curious as to what you expect to happen if I write something like:

    int
    main()
    {
        C c1;
        C c2
        c1.some_method( &c2 );
    }
    

    Do you expect the address of c1 to somehow miraculously change, and for c1 and c2 to be aliases to the same object? (And c1.some_method( NULL ) is even more intreguing.)

    0 讨论(0)
提交回复
热议问题