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

后端 未结 6 1387
花落未央
花落未央 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: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.)

提交回复
热议问题