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

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

提交回复
热议问题