Espaços nominais
Variantes
Acções

Destructors

Da cppreference.com
< cpp‎ | language

 
 
Linguagem C + +
Tópicos gerais
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.
Controle de fluxo
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.
Declarações execução condicional
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.
Instruções de iteração
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 declarações
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.
Funções
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaração da função
lambda declaração da função
modelo de função
linha especificador
especificações de exceção (obsoleta)
noexcept especificador (C++11)
Exceções
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Namespaces
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)
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
armazenamento duração especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialização
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Literais
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expressões
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representações alternativas
Utilitários
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
tipo de alias declaração (C++11)
atributos (C++11)
Lança
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversões implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
Elenco C-estilo e funcional
Alocação de memória
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.
Classes
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classe propriedades específicas de função
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.
Funções membro especiais
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.
Modelos
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
modelo de classe
modelo de função
especialização de modelo
pacotes de parâmetros (C++11)
Diversos
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Assembly embutido
 
Um destrutor é uma função membro especial que é chamado quando o tempo de vida de um objeto termina. O objetivo do destruidor é para liberar os recursos que o objeto possa ter adquirido durante a sua vida.
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.

Índice

[editar] Sintaxe

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

[editar] Explicação

# Declaração típica de um destruidor
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.
Destruidor # Virtual é geralmente necessária em uma classe 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.
# Forçando um destruidor a ser gerado pelo 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.
# Desabilitando o destruidor implícita
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.
O destrutor é chamado sempre que a vida de um objeto termina, o que inclui
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.
  • término do programa, para objetos com duração de armazenagem estática
    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.
  • saída de rosca, para objetos com segmento local (a partir do C++ 11) duração de armazenamento
    Original:
    thread exit, for objects with thread-local storage duration (a partir do 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 do escopo, para objetos com duração de armazenamento automático e para temporários cuja vida foi prorrogado por ligação a uma referência
    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.
  • apagar-expressão, para objetos com duração de armazenamento 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.
  • fim da expressão completa, por temporários sem nome
    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.
  • empilhar descontrair, para objetos com duração de armazenamento automático quando uma exceção escapa de seu bloco não capturado,.
    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.
O destrutor também pode ser chamado diretamente, por exemplo, para destruir um objeto que foi construído utilizando-colocação nova ou através de uma função de membro alocador como std :: alocador :: destroy (), para destruir um objeto que foi construído através do alocador. Note que chamar um destruidor diretamente para um objeto comum, como uma variável local, invoca o comportamento indefinido quando o destruidor é chamado novamente, no final do escopo.
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 :: alocador :: 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] Implicitamente declarado destruidor

Se não definido pelo usuário destruidor é fornecido para um tipo de classe (struct, class, ou union), o compilador sempre declarar um destruidor como um membro de sua classe inline public.
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] Excluídos destruidor cópia implicitamente declarado

O destrutor implicitamente declarado ou inadimplente para T classe é (até C + 11) indefinido / definido como excluídos (a partir do C++ 11) se qualquer uma das seguintes situações:
Original:
The implicitly-declared or defaulted destructor for class T is undefined (até C + 11) / defined as deleted (a partir do 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 tem um não-estático membro de dados que não pode ser destruído (já eliminado ou destruidor inacessível)
    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 tem classe base direta ou virtual que não pode ser destruído (já eliminado ou destruidores inacessíveis)
    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 é uma união e tem um membro variante com não-trivial (a partir do C++ 11) destruidor
    Original:
    T is a union and has a variant member with non-trivial destructor (a partir do C++ 11)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • O destrutor implicitamente declarado é virtual (porque a classe base tem um destrutor virtual) ea pesquisa para a função de desalocação (operator delete() resulta em uma chamada para ambígua, excluídos ou função inacessível.
    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] Destruidor trivial

Destruidor O implicitamente declarado para a classe T é trivial se todo o seguinte é verdadeiro:
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.
  • O destruidor não é virtual (isto é, o destruidor de classe base não é 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 as classes base diretas têm destruidores virtuais
    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 os membros não-estáticos de dados..... tipo de classe (ou matriz de tipo de classe) tem destruidores virtuais
    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.
Uma destruidor trivial é um destruidor que não executa nenhuma ação. objetos com destruidores triviais não exigem uma exclusão-expressão e podem ser eliminados por simplesmente desalocando seu armazenamento. Todos tipos de dados compatíveis com a linguagem C (tipos POD) são trivialmente destrutíveis.
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] Implicitamente definido destruidor

Se o destruidor implicitamente declarado não é excluído ou trivial, é definido (isto é, um corpo de função é gerado e compilado) pelo compilador. Este destrutor implicitamente definido tem um corpo vazio.
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] Seqüência de destruição

Para ambos os destruidores definidos pelo usuário ou implicitamente definido, depois que o corpo do destrutor é executado, o compilador chama os destrutores de todos os não-estáticos variante não-membros da classe, na ordem inversa da declaração, então ele chama os destruidores de todas as classes base diretas na ordem inversa de construção (que por sua vez chama os destruidores de seus membros e suas classes base, etc), e depois, se esse objeto é de mais derivado classe, ele chama os destruidores de todas as bases virtuais.
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.
Mesmo quando o destruidor é chamado diretamente (por exemplo obj.~Foo();), a declaração de retorno em ~Foo() não retorna o controle para o chamador imediato:. que chama todos os membros e destruidores primeira 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] Destrutores virtuais

Excluindo um objeto através de ponteiro para a base invoca um comportamento indefinido, a menos que o destruidor na classe base é 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

Uma diretriz comum é que um destruidor de uma classe base deve 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] Pura destruidores virtuais

Um destruidor pode ser declarado virtual pura... , por exemplo, numa classe de base, que tem de ser feito abstracto, mas não tem outras funções adequadas que podem ser declarados puro virtual destructor Tal deve ter uma definição, uma vez que todos os destruidores de classe base sempre são chamados quando a classe derivada é destruído.:
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] Exemplo

#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