Espaços nominais
Variantes
Acções

std::unique_ptr

Da cppreference.com
< cpp‎ | memory


 
 
Biblioteca de utilitários
Digite apoio (basic types, RTTI, type traits)
Gerenciamento de memória dinâmica
De tratamento de erros
Utilidades do programa
Variadic funções
Data e hora
Objetos de função
(C++11)
Os operadores relacionais
Original:
Relational operators
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
rel_ops::operator!=
rel_ops::operator>
rel_ops::operator<=
rel_ops::operator>=
Pares e tuplas
Original:
Pairs and tuples
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
(C++11)
Troque, avançar e avançar
Original:
Swap, forward and move
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
(C++11)
(C++11)
(C++11)
 
Gerenciamento de memória dinâmica
Gerenciamento de memória de baixo nível
Alocadores
Original:
Allocators
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Uninitialized armazenamento
Original:
Uninitialized storage
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Ponteiros inteligentes
Original:
Smart pointers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
unique_ptr
(C++11)
(C++11)
(C++11)
(obsoleta)
(C++11)
Apoio a coleta de lixo
Original:
Garbage collection support
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
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.
(C++11)
(C++11)
C Library
Original:
C Library
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
 
std :: unique_ptr
Funções de membro
Original:
Member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
unique_ptr::unique_ptr
unique_ptr::~unique_ptr
unique_ptr::operator=
Modificadores
Original:
Modifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
unique_ptr::release
unique_ptr::reset
unique_ptr::swap
Observadores
Original:
Observers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
unique_ptr::get
unique_ptr::get_deleter
unique_ptr::operator bool
unique_ptr::operator*
unique_ptr::operator->
unique_ptr::operator[]
Não-membros funções
Original:
Non-member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
 
Definido no cabeçalho <memory>
template<

    class T,
    class Deleter = std::default_delete<T>

> class unique_ptr;
(1) (desde C++11)
template <

    class T,
    class Deleter

> class unique_ptr<T[],Deleter>;
(2) (desde C++11)

std::unique_ptr é um ponteiro inteligente que:

  • detém a propriedade exclusiva de um objeto através de um ponteiro, e
  • destrói o objeto apontado quando o unique_ptr sai do escopo.

O unique_ptr não pode ser copiado nem transferido por cópia. Um objeto não pode ser gerido por duas instâncias diferentes de unique_ptr. Um unique_ptr não-const pode transferir a propriedade do objeto gerido para outro unique_ptr; já um const std::unique_ptr não pode ser transferido, o que limita o tempo de vida do objeto gerido ao escopo onde o ponteiro foi criado. Quando o unique_ptr é destruído, ele descarta o objeto através de Deleter. Existem duas versões do std::unique_ptr:

1) gere o tempo de vida de um único objeto (por exemplo, alocado com new)
2) controla o tempo de vida de uma matriz cujo comprimento é decidido durante a execução (por exemplo, alocado com new [])

Os usos típicos de std::unique_ptr incluem:

  • proporcionando segurança exceção a classes e funções que manipulam objetos com vida dinâmica, garantindo a eliminação de ambos saída normal e saída através de exceção.
    Original:
    providing exception safety to classes and functions that handle objects with dynamic lifetime, by guaranteeing deletion on both normal exit and exit through exception.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • passando a propriedade de objetos de propriedade exclusiva com vida dinâmica em funções
    Original:
    passing ownership of uniquely-owned objects with dynamic lifetime into functions
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • a aquisição da propriedade de objetos de propriedade exclusiva com vida dinâmica de funções
    Original:
    acquiring ownership of uniquely-owned objects with dynamic lifetime from functions
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • como o tipo de elemento em movimento de reconhecimento de recipientes, como std::vector, que possuem ponteiros para objetos dinamicamente alocados, por exemplo, se o comportamento polimórfico é desejado
    Original:
    as the element type in move-aware containers, such as std::vector, which hold pointers to dynamically-allocated objects, e.g. if polymorphic behavior is desired
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

Índice

[editar] Tipos de membro

Tipo de membro
Original:
Member type
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Definition
pointer
std::remove_reference<D>::type::pointer se esse tipo existe, de outra forma * T
Original:
std::remove_reference<D>::type::pointer if that type exists, otherwise T*
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
element_type
T, o tipo do objeto gerenciado por este unique_ptr
Original:
T, the type of the object managed by this unique_ptr
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
deleter_type
Deleter, o objeto de função ou lvalue referência à função ou objeto de função, a ser chamado a partir do destruidor
Original:
Deleter, the function object or lvalue reference to function or to function object, to be called from the destructor
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Funções de membro

constrói um novo unique_ptr
Original:
constructs a new unique_ptr
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]
destrói o objeto gerenciado se for presente
Original:
destructs the managed object if such is present
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]
atribui o unique_ptr
Original:
assigns the unique_ptr
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]
Modificadores
Original:
Modifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
retorna um ponteiro para o objeto gerenciado e libera a propriedade
Original:
returns a pointer to the managed object and releases the ownership
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]
substitui o objeto gerenciado
Original:
replaces the managed object
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]
troca os objetos gerenciados
Original:
swaps the managed objects
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]
Observadores
Original:
Observers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
retorna um ponteiro para o objeto gerenciado
Original:
returns a pointer to the managed object
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]
retorna o deleter que é usado para a destruição do objecto gerido
Original:
returns the deleter that is used for destruction of the managed object
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]
verifica se existe é associado objeto gerenciado
Original:
checks if there is associated managed object
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]
Único objeto de versão, unique_ptr <T>
Original:
Single-object version, unique_ptr<T>
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
dereferences ponteiro para o objeto gerenciado
Original:
dereferences pointer to the managed object
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]
Versão matriz, unique_ptr <T[]>
Original:
Array version, unique_ptr<T[]>
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
fornece acesso indexado à matriz gerenciada
Original:
provides indexed access to the managed array
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(função pública membro) [edit]

[editar] Não-membros funções

compara a outra ou com unique_ptr nullptr
Original:
compares to another unique_ptr or with nullptr
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]
o algoritmo especializado std::swap
Original:
specializes the std::swap algorithm
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(modelo de função) [edit]

[editar] Classes auxiliares

apoio de hash para std::unique_ptr
Original:
hash support for std::unique_ptr
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(especialização modelo. classe) [edit]

[editar] Exemplo

#include <iostream>
#include <memory>
 
struct Foo {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; }
    void bar() { std::cout << "Foo::bar\n"; }
};
 
void f(const Foo &foo)
{
    std::cout << "f(const Foo&)\n";
}
 
int main()
{
    std::unique_ptr<Foo> p1(new Foo);  // p1 owns Foo
    if (p1) p1->bar();
 
    {
        std::unique_ptr<Foo> p2(std::move(p1));  // now p2 owns Foo
        f(*p2);
 
        p1 = std::move(p2);  // ownership returns to p1
        std::cout << "destroying p2...\n";
    }
 
    if (p1) p1->bar();
 
    // Foo instance is destroyed when p1 goes out of scope
}

Saída:

Foo::Foo
Foo::bar
f(const Foo&)
destroying p2...
Foo::bar
Foo::~Foo