Search code examples
c++free

C++: delete this; return x;


Hey I am curious about some C++ behaviour as the code I am working on would benefit greatly from this in terms of simplicity if this behaviour is consistent. Basically the idea is for a specific function inside my object A to compute a complex calculation returning a float, but just before returning the float, occasionally, calling delete this.


1

here is a code example of the functionality i am trying to verify is consistent.

#include <iostream>
#include <stdio.h>
#include <cstdlib>

using namespace std;

struct A
{
    float test(float a) {delete this; return a;}
};

int main()
{
    A *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 this means the object was deleted correctly (what is left in memory? an uncallable skeleton of A? A typed pointer? A null pointer?), but am not sure whether I am right about that. If so, is this behaviour going to be consistent (my functions will only be returning native types (floats))


2

Additionally I am curious as to why this doesn't seem to work:

struct A
{
    float test(float a) {delete this; return a;}
};

int main()
{
    A a;
    cout << a.test(1.f) << endl;
}

this compiles but throws the following error before returning anything.

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

NOTE Please don't tell reply with a long list of explanations as to why this is bad coding/etiquette or whatever, don't care, I am simply interested in the possibilities.


Solution

  • It is safe for a member function to call delete this; if you know that the object was allocated using scalar new and that nothing else will use the object afterward.

    In your first example, after the first call to a->test(1.f), a becomes a "dangling pointer". You invoke Undefined Behavior when you dereference it to call test a second time.

    In your second example, the delete this; statement is Undefined Behavior because the object was not created using new.