¿Eliminar es una función miembro? destructor en privado no se invocará con eliminar?

Given the next code :

#include <iostream>
using namespace std;

class A
{
private:
    ~A () {}
};

int main()
{

    A *a = new A();
    delete a;
    return 0;

}

It doesn't compile .I thought that delete is a member function , isn't ? If so , shouldn't it have access to the dtor of A ?

Regrads ,Ron

preguntado el 27 de agosto de 11 a las 21:08

6 Respuestas

NO, delete is not a member function; it's an operator. There is an operator delete() function which is invoked by the delete operator, but it's not a member unless you define it as such.

Respondido 28 ago 11, 01:08

By that logic, this would be valid code:

class Foo
{
    Foo()
    {
    }
}

int main()
{
    // new is also a member function, right?
    Foo* Bar = new Foo;
}

Respondido 28 ago 11, 01:08

Solution to the riddle: no, delete is not a member function

Delete is an operator, that can be overloaded for a type, but not as a member function

Respondido 28 ago 11, 01:08

If you say to the compiler that a method is private, only the class can call it.

In you case, that means that only your class can delete itself.

Respondido 28 ago 11, 01:08

This has nothing to do with the delete operator. Rather, the problem is that the incinerador de basuras is private, and when you call the delete expresión delete a;, esto es equivalente a a->~A(); ::operator delete(a); It is this first call to the destructor that fails, rather than the call of the delete operator.

Even if you overloaded member new/delete operators, that wouldn't change a thing, because it's the delete expresión which first calls the destructor and then the (member) operator, so the destructor must be available as a public function.

Respondido 28 ago 11, 02:08

Conceptually, it is equivalent. Technically, no lo es. - fredoverflow

You are confusing the call to delete, with the implementation of the delete method.

If you call delete, actually 2 things will happen:

  • the destructor is called
  • la memoria se libera

By default, the memory will be freed by a default delete method. If you implement the delete method, your implementation should only free the memory, not call any destructor.

That's why you need access to both the delete method AND the destructor before you can call delete.

Respondido 28 ago 11, 01:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.