Can an object free memory?

Possible duplicates:
C ++: Delete this?
Object-oriented suicide or remove it;

I learn C ++ by reading the very good C ++ Primer book and I will learn how C ++ frees memory from a keyword deletesuch as C, c free. Java and Pascal do not have this mechanism for explicitly freeing memory. This can lead to errors in programs if they work for a long time, and the variables are destroyed, which is necessary so that it is not trivial.

In short, I wonder if it is legal or appropriate, for example, in C ++ for a variable to make this.delete()and delete itself. We mainly hear about the release of pointers to C and C ++, and this is done with new keywords freeand delete. Pascal also has pointers, but Java does not. Therefore, in Java, this should not be possible, since you do not explicitly delete objects, C has no objects, therefore, structcould not freeallocate memory, even if it was technically possible, since C has no objects and Pascal too.

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

+5
source share
6 answers

, delete this;.

this - undefined.

, , , , " ", delete this;

, , , , , : .

, :

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;
}
+6

this .

 delete this;

, , .

. this.

- , , .

+5

, - this.delete()?

, delete this. , , FAQ.

, delete this . - . , , ++.

+3

, , - , , .

, this , .

0

, . .

- . release(), , . -, this ( , delete foo ). :

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

( , - delete - , , this - .)

, . , this . (, , ..).

0
source

Another way for an object to remove its memory is to use something called Resource Aquisition Is Initialitation. RAII

With this method you are not newor an deleteobject. This destructor is automatically called when it goes out of scope.

i.e. You would use RAIIin functions like:

void foo()

{

  `Object a;`

  `int i = a.SomeMethod();`

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

}

additional literature

0
source

All Articles