0

Can I reallocate object itself?

Recently i studied about copy constructor and i get curious about deleting 'this' and reallocating it.

obj(const obj &s) {
    if(this != NULL)
        delete this;
    this = new obj();
}

And it says [Error] lvalue required as left operand of assignment. Is it impossible to reallocate itself? if so, why is that?

  • `this` is a prvalue, so you can't assign a value to it. It would be the same as trying to do `0 = 10;`. – super Jul 07 '19 at 09:17
  • 1
    I think you can call the destructor explicitly and than do a placement new, that said, ain't a good idea to surprise your callers by such a behavior – JVApen Jul 07 '19 at 09:21
  • Relevant [Is it allowed to call destructor explicitly followed by placement new on a variable with fixed lifetime?](https://stackoverflow.com/questions/42598915/is-it-allowed-to-call-destructor-explicitly-followed-by-placement-new-on-a-varia). – Quimby Jul 07 '19 at 10:16
  • FYI if you want to do so, some non-standard optimizations can't work, for example: https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fstrict-vtable-pointers – JVApen Jul 07 '19 at 16:45

1 Answers1

2

delete operator works only for objects allocated using operator new, otherwise behavior is undefined.

Once delete this; is done, none of the members should be accessed. If accessed, it will cause exception and leads to crash.

But you cannot assign to this pointer. this is a prvalue expression whose value is the address of the object for which the function is called.

SolidMercury
  • 973
  • 6
  • 15