Could an object deallocate its memory? [duplicate]
Asked Answered
C

6

5

Possible Duplicates:
C++: Delete this?
Object-Oriented Suicide or delete this;

I'm learning C++ by reading the very good book C++ Primer and I'm learning how C++ deallocates memory by the delete keyword like C does with free. Java and Pascal do not have this mechanism for explcitly freeing memory. It could lead to errors in programs if they run for long time and variables are destroyed that are needed so it should not be trivialized.

In short I wonder if it's legal or advicable for instance in C++ for a variable to do this.delete() and delete itself. We mostly hear about freeing pointers in C and C++ and this is done with new free and delete keywords. Pascal also has pointers but Java has not. So in Java it should not be possible since you do not explicitly delete objects, C doesn't have objects so a struct couldn't free the memory it was allocated even if it was technically possible since C does not have objects and neither does Pascal.

So I suppose that leaves C++ for my question whether it is legal for an object to delete itself with something like this.delete()?

Cornwell answered 28/5, 2012 at 10:56 Comment(1)
Doing so is possible - delete this; is perfectly valid syntax in C++ and should compile and execute "correctly". However, it assumes that *this is allocated in the heap which ain't necessarily so. Further, it risks further memory corruption because once freed the space formerly occupied by *this can be re-used by later memory allocations. Bad idea. Run away! Run away!Cuesta
S
6

It's perfectly possible for an object to do delete this;.

However, after doing so, using thisis an undefined behaviour.

So, if you are very careful with was is done afterward, it's fine and legal for an object to "commit suicide" by doing delete this;

But, It's really not a good idea, especially because it means that your class should only be instanciated by new, as an allocation on te stack could cause the destructor to be called twice: by the delete this, and when going out of context.

The following example shows why it's not a good idea:

class A
{
public:
    ~A() { std::cout << "Destructor"; }
    void foo() { delete this; } 
};

int main()
{
    {
        A a;
        a.foo(); // OK, a is deleted
    } // Going out of context, the destructor is called again => undefined behavior
    return 0;
}
Shaddock answered 28/5, 2012 at 10:58 Comment(5)
Thank you for the answer. I notice that in C++ compared to other languages it is not unusual to risk "undefined bevaviour."Cornwell
@NickRosencrantz: It is extremely unusual to willingly risk undefined behaviour in production code.Burley
@NickRosencrantz: in most other languages, undefined behavior doesn't exist. In C++, it should be avoided like the plague, because it is, by definition, unreliable. You can't trust your program once it's entered undefined behavior.Isolde
@jalf I won't deliberately start it, I just never heard about undefined behavior before I studied C++ and therefore I thought I risked it. I've seen C, Pascal, assembler, Java and other languages and none of them had undefined behavior even for bugs. I suppose it's OK that undefined behavior exists in a language.Cornwell
@NickRosencrantz: C certainly has undefined behavior. I'm not sure about Pascal. Java does not, and assembler does notIsolde
B
5

this is a pointer. The proper syntax would be

 delete this;

And yes, it's possible, but it renders your object and pointers to your object unusable.

See this for a good read.

In practice, using this technique is a code smell, unless you're absolutely sure what you're doing.

Beverlybevers answered 28/5, 2012 at 10:58 Comment(1)
That's interesting and good to know. Thanks for the answer.Cornwell
B
3

my question whether it is legal for an object to delete itself with something like this.delete()?

Technically, it is legal for an object to perform delete this. However, there is a number of hugely important caveats that are explained in the FAQ.

It is also important to understand that delete this solves a very narrow technical problem. It does not really solve any big-picture questions about memory management and garbage collection. One direction worthy of further study is the use of smart pointers in C++.

Burley answered 28/5, 2012 at 10:59 Comment(0)
T
0

Although odd one use case would be say for a dialog box where the user clicks OK or whatever and this action causes the dialog box to delete itself but it is legal.

Of course the this pointer is no longer valid so you shouldn't try to use it.

Tuyettv answered 28/5, 2012 at 10:59 Comment(0)
P
0

It is entirely possible for an object to deallocate its own memory. However, it is very rarely used, for obvious reasons.

The most common usage is for implementing reference-counted memory management. When the caller invokes release() and the reference count hits zero, the object is deleted. Since this happens inside a member variable, it uses the this pointer to delete the instance (much in the same way you would call delete foo outside the object). For example:

int release()
{
    OSAtomicDecrement32(&m_refCount);
    if (m_refCount <= 0)
    {
        delete this;
    }
    return m_refCount;
}

(Note that the syntax you mention is not valid - delete is a keyword, not a method, and this is a pointer.)

There are several caveats to keep in mind though. Once this deletion has been called, the this pointer is no longer valid, nor are any of the data members. From that point onward, only non-instance references can be made (eg. to local variables, static methods and data, etc).

Pillage answered 28/5, 2012 at 11:5 Comment(0)
P
0

Another way for the object to delete its memory is using something called Resource Aquisition Is Initialisation RAII

With this method you do not new or delete the object. It's destructor automatically gets called when it leaves its scope.

i.e. You would use RAII in a function like:

void foo()

{

  `Object a;`

  `int i = a.SomeMethod();`

  `// a's destructor automatically gets called when the function is out of scope`

}

Further Reading

Prochora answered 28/5, 2012 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.