Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self delete an object in C++ [duplicate]

Tags:

c++

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

I wonder if the code below is run safely:

#include <iostream>
using namespace std;

class A
{
public:
    A() {
        cout << "Constructor" << endl;
    }
    ~A() {
        cout << "Destructor" << endl;
    }

    void deleteMe() {
        delete this;
        cout << "I was deleted" << endl;
    }
};

int main()
{
    A *a = new A();
    a->deleteMe();
    cout << "Exit ...";
    return 0;
}

Output is:

Constructor
Destructor
I was deleted
Exit ...

and program exit normally, but are there some memory access violents here?

like image 433
Bình Nguyên Avatar asked Aug 01 '12 09:08

Bình Nguyên


People also ask

Can an object destroy itself?

A self-destruct is a mechanism that can cause an object to destroy itself or render itself inoperable after a predefined set of circumstances has occurred. Self-destruct mechanisms are typically found on devices and systems where malfunction could endanger large numbers of people.

Is destructor called when using delete?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

Can I call delete this?

It's safe to delete "this" as long as it's essentially the last operation in the method. In fact several professional level APIs do so (see ATL's CComObject implementation for an example). The only danger is attempting to access any other member data after calling "delete this". This is certainly unsafe.

How to remove an object in an array C++?

You can't remove an item of an array using standard C++ arrays. Use std::vector instead. An array like initialized with new[] is a buffer which pointer points at its first memory cell. In vectors and lists, elements are linked.


2 Answers

It's ok to delete this in case no one will use the object after that call. And in case the object was allocated on a heap of course

For example cocos2d-x game engine does so. It uses the same memory management scheme as Objective-C and here is a method of base object:

void CCObject::release(void)
{
    CCAssert(m_uReference > 0, "reference count should greater than 0");
    --m_uReference;

    if (m_uReference == 0)
    {
        delete this;
    }
}

I don't think it's a c++ way of managing memory, but it's possible

like image 166
Andrew Avatar answered Nov 05 '22 13:11

Andrew


It's ok, because you have running simple method. After delete this, all variables and virtual table are clear. Just, analyze this example:

#include <iostream>

class foo
{
public:
    int m_var;
    foo() : m_var(1)  
    {

    }

    void deleteMe()
    {
        std::cout << m_var << "\n";
        delete this;
        std::cout << m_var << "\n"; // this may be crush program, but on my machine print "trash" value, 64362346 - for example
    }

    virtual void bar()
    {
        std::cout << "virtual bar()\n";
    }



  void anotherSimpleMethod()
    {
       std::cout << "anotherSimpleMethod\n";
    }

    void deleteMe2()
    {
        bar();
        delete this;
        anotherSimpleMethod();
        // bar(); // if you uncomment this, program was crashed, because virtual table was deleted
    }
};

int main()
{
    foo * p = new foo();
    p->deleteMe();
    p = new foo();
    p->deleteMe2();
    return 0;
}

I've can't explain more details because it's need some knowledge about storing class and methods in RAM after program is loaded.

like image 36
Torsten Avatar answered Nov 05 '22 14:11

Torsten