Espacios de nombres
Variantes
Acciones

Destructors

De cppreference.com
< cpp‎ | language

 
 
Lenguaje C++
Los temas generales
Original:
General topics
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Control de flujo
Original:
Flow control
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Sentencias condicionales ejecución
Original:
Conditional execution statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Instrucciones de iteración
Original:
Iteration statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Ir declaraciones
Original:
Jump statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funciones
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaración de la función
lambda declaración de la función
función de plantilla
especificador inline
especificaciones de excepción (obsoleto)
noexcept especificador (C++11)
Excepciones
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los espacios de nombres
Original:
Namespaces
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
decltype specifier (C++11)
Los especificadores
Original:
Specifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
cv especificadores
almacenamiento duración especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialización
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los literales
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expresiones
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representaciones alternativas
Utilidades
Original:
Utilities
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
typedef declaration
alias de tipo de declaración (C++11)
atributos (C++11)
Lanza
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversiones implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-cast estilo y funcional
De asignación de memoria
Original:
Memory allocation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Clases
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Clase propiedades específicas de la función
Original:
Class-specific function properties
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funciones especiales miembro
Original:
Special member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Plantillas
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
clase de plantilla
función de plantilla
plantilla de especialización
paquetes de parámetros (C++11)
Varios
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Montaje en línea
 
Un destructor es una función miembro especial que se llama cuando el tiempo de vida de un objeto termina. El propósito del destructor es para liberar los recursos que el objeto puede haber adquirido durante su vida útil .
Original:
A destructor is a special member function that is called when the lifetime of an object ends. The purpose of the destructor is to free the resources that the object may have acquired during its lifetime.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Contenido

[editar] Sintaxis

~class_name (); (1)
virtual ~class_name (); (2)
~class_name () = default; (3) (desde C++11)
~class_name () = delete; (4) (desde C++11)

[editar] Explicación

# Declaración típica de un destructor
Original:
# Typical declaration of a destructor
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
# Destructor virtual se requiere generalmente en una clase base
Original:
# Virtual destructor is usually required in a base class
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
# Obligar a un destructor que serán generados por el compilador
Original:
# Forcing a destructor to be generated by the compiler
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
# Deshabilitar el destructor implícito
Original:
# Disabling the implicit destructor
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
El destructor se llama cuando la vida de un objeto termina, lo que incluye
Original:
The destructor is called whenever an object's lifetime ends, which includes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • finalización del programa, para objetos con una duración de almacenamiento estático
    Original:
    program termination, for objects with static storage duration
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • salida de rosca, para objetos de subproceso local (desde C++11) duración de almacenamiento
    Original:
    thread exit, for objects with thread-local storage duration (desde C++11)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • final de su alcance, para objetos con una duración de almacenamiento automático y para temporales cuya vida se extendió mediante la unión a una referencia
    Original:
    end of scope, for objects with automatic storage duration and for temporaries whose life was extended by binding to a reference
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • delete-expresión, para objetos con una duración de almacenamiento dinámico
    Original:
    delete-expression, for objects with dynamic storage duration
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • final de la expresión completa, para los temporales sin nombre
    Original:
    end of the full expression, for nameless temporaries
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • desenredo de pila, para objetos con una duración de almacenamiento automático cuando una excepción escapa a su bloque, no detectada .
    Original:
    stack unwinding, for objects with automatic storage duration when an exception escapes their block, uncaught.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
El destructor también se puede llamar directamente, por ejemplo, para destruir un objeto que fue construido con la colocación de nuevo o por medio de una función miembro asignador como std :: asignador :: destroy (), para destruir un objeto que se construye a través de la imputación. Tenga en cuenta que llamar a un destructor directamente para un objeto ordinario, como una variable local, invoca un comportamiento indefinido cuando se llama al destructor de nuevo, al final del alcance .
Original:
The destructor may also be called directly, e.g. to destroy an object that was constructed using placement-new or through an allocator member function such as std :: asignador :: destroy (), to destroy an object that was constructed through the allocator. Note that calling a destructor directly for an ordinary object, such as a local variable, invokes undefined behavior when the destructor is called again, at the end of scope.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Implícitamente, declarado destructor

Si no hay definida por el usuario destructor se preveía un tipo de clase (struct, class o union), el compilador siempre declarar un destructor como miembro inline public de su clase .
Original:
If no user-defined destructor is provided for a class type (struct, class, or union), the compiler will always declare a destructor as an inline public member of its class.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Suprimido destructor implícitamente declarada copia

El destructor implícitamente declaradas o cesación de pagos por T clase es (hasta C++11) undefined / define como borrado (desde C++11) si alguna de las siguientes situaciones:
Original:
The implicitly-declared or defaulted destructor for class T is undefined (hasta C++11) / defined as deleted (desde C++11) if any of the following is true:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • T tiene un miembro no estático datos que no pueden ser destruidos (ha eliminado o destructor inaccesible)
    Original:
    T has a non-static data member that cannot be destructed (has deleted or inaccessible destructor)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • T tiene clase base directa o virtual que no puede ser destruido (se ha suprimido o destructores inaccesibles)
    Original:
    T has direct or virtual base class that cannot be destructed (has deleted or inaccessible destructors)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • T es un sindicato y tiene un miembro variante con (desde C++11) destructor no trivial
    Original:
    T is a union and has a variant member with non-trivial destructor (desde C++11)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • El destructor implícitamente declarado es virtual (porque la clase base tiene un destructor virtual) y la búsqueda de la función de cancelación de asignación (operator delete() resulta en una llamada a la ambigüedad, eliminadas o función inaccesible .
    Original:
    The implicitly-declared destructor is virtual (because the base class has a virtual destructor) and the lookup for the deallocation function (operator delete() results in a call to ambiguous, deleted, or inaccessible function.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[editar] Destructor trivial

-El destructor implícitamente declarado para la clase T es trivial si todo lo siguiente es cierto:
Original:
The implicitly-declared destructor for class T is trivial if all of the following is true:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • El destructor no es virtual (es decir, el destructor de la clase base no es virtual)
    Original:
    The destructor is not virtual (that is, the base class destructor is not virtual)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Todas las clases base directas tienen destructores virtuales
    Original:
    All direct base classes have virtual destructors
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Todos los miembros no estáticos de datos..... tipo de clase (o matriz de tipo de clase) tienen destructores virtuales
    Original:
    All non-static data members of class type (or array of class type) have virtual destructors
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Un destructor trivial es un destructor que no realiza ninguna acción. Objetos con destructores triviales no requieren una eliminación de expresión y pueden ser eliminados simplemente liberando su almacenamiento. Todos tipos de datos compatibles con el lenguaje C (tipos POD) son trivialmente destructible .
Original:
A trivial destructor is a destructor that performs no action. Objects with trivial destructors don't require a delete-expression and may be disposed of by simply deallocating their storage. All data types compatible with the C language (POD types) are trivially destructible.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Implícitamente definido destructor

Si el destructor implícitamente declarada no se elimina o trivial, está definido (es decir, un cuerpo de función es generado y compilado) por el compilador. Este destructor implícitamente definido tiene un cuerpo vacío .
Original:
If the implicitly-declared destructor is not deleted or trivial, it is defined (that is, a function body is generated and compiled) by the compiler. This implicitly-defined destructor has an empty body.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Destrucción secuencia

Tanto para los destructores definidos por el usuario o implícitamente definida, después de que el cuerpo del destructor se ejecuta, el compilador llama a los destructores para todos los no estáticos no variante miembros de la clase, en el orden inverso de la declaración, a continuación, llama a los destructores de todas las clases base directas en orden inverso al de la construcción (que a su vez llama a los destructores de sus miembros y sus clases base, etc), y luego, si este objeto es de más derivados clase, llama a los destructores de todas las bases virtuales .
Original:
For both user-defined or implicitly-defined destructors, after the body of the destructor is executed, the compiler calls the destructors for all non-static non-variant members of the class, in reverse order of declaration, then it calls the destructors of all direct base classes in reverse order of construction (which in turn call the destructors of their members and their base classes, etc), and then, if this object is of most-derived class, it calls the destructors of all virtual bases.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Incluso cuando se llama al destructor directamente (por ejemplo obj.~Foo();), la sentencia de retorno en ~Foo() no devuelve el control al llamador inmediato:. llama a todos esos destructores miembros y la primera base. .
Original:
Even when the destructor is called directly (e.g. obj.~Foo();), the return statement in ~Foo() does not return control to the caller immediately: it calls all those member and base destructors first.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Destructores virtuales

Eliminación de un objeto a través del puntero a la base invoca un comportamiento indefinido a menos que el destructor de la clase base es virtual:
Original:
Deleting an object through pointer to base invokes undefined behavior unless the destructor in the base class is virtual:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

class Base {
 public:
    virtual ~Base() {}
};
class Derived : public Base {};
Base* b = new Derived;
delete b; // safe

Una pauta común es que el destructor de la clase base debe ser either public and virtual or protected and nonvirtual
Original:
A common guideline is that a destructor for a base class must be either public and virtual or protected and nonvirtual
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Pure destructores virtuales

Un destructor puede ser declarado puro virtual... , por ejemplo, en una clase base que necesita ser hecha abstracto, pero no tiene otras funciones adecuadas que puedan ser declarados virtual pura destructor Tal debe tener una definición, ya que todos los destructores de la clase base siempre son llamados cuando la clase derivada se destruye.:
Original:
A destructor may be declared pure virtual, for example in a base class which needs to be made abstract, but has no other suitable functions that could be declared pure virtual. Such destructor must have a definition, since all base class destructors are always called when the derived class is destroyed:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

class AbstractBase {
 public:
    virtual ~AbstractBase() = 0;
};
AbstractBase::~AbstractBase() {}
class Derived : public AbstractBase {};
// AbstractBase obj;   // compiler error
Derived obj;           // OK

[editar] Ejemplo

#include <iostream>
 
struct A
{
    int i;
 
    A ( int i ) : i ( i ) {}
 
    ~A()
    {
        std::cout << "~a" << i << std::endl;
    }
};
 
int main()
{
    A a1(1);
    A* p;
 
    { // nested scope
        A a2(2);
        p = new A(3);
    } // a2 out of scope
 
    delete p; // calls the destructor of a3
}

Output:

~a2
~a3
~a1