free - C++: delete this; return x; -


hey curious c++ behaviour code working on benefit in terms of simplicity if behaviour consistent. idea specific function inside object a compute complex calculation returning float, before returning float, occasionally, calling delete this.


1

here code example of functionality trying verify consistent.

#include <iostream> #include <stdio.h> #include <cstdlib>  using namespace std;  struct {     float test(float a) {delete this; return a;} };  int main() {     *a = new a();     cout << a->test(1.f) << endl;     cout << "deleted?" << endl;     cout << a->test(1.f) << endl; } 

the output becomes:

1.0 deleted? *** error in `./test': double free or corruption (fasttop): 0x0105d008 *** aborted (core dumped) 

i think means object deleted correctly (what left in memory? uncallable skeleton of a? typed pointer? null pointer?), not sure whether right that. if so, behaviour going consistent (my functions returning native types (floats))


2

additionally curious why doesn't seem work:

struct {     float test(float a) {delete this; return a;} };  int main() {     a;     cout << a.test(1.f) << endl; } 

this compiles throws following error before returning anything.

*** error in `./test': free(): invalid pointer: 0xbe9e4c64 *** aborted (core dumped) 

note please don't tell reply long list of explanations why bad coding/etiquette or whatever, don't care, interested in possibilities.

it safe member function call delete this; if know object allocated using scalar new , nothing else use object afterward.

in first example, after first call a->test(1.f), a becomes "dangling pointer". invoke undefined behavior when dereference call test second time.

in second example, delete this; statement undefined behavior because object not created using new.


Comments