Espaços nominais
Variantes
Acções

std::shared_ptr::shared_ptr

Da cppreference.com
< cpp‎ | memory‎ | shared ptr

 
 
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
initializer_list(C++11)
bitset
hash(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.
pair
tuple(C++11)
piecewise_construct_t(C++11)
piecewise_construct(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.
swap
forward(C++11)
move(C++11)
move_if_noexcept(C++11)
declval(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.
allocator
allocator_traits(C++11)
allocator_arg_t(C++11)
allocator_arg(C++11)
uses_allocator(C++11)
scoped_allocator_adaptor(C++11)
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.
uninitialized_copy
uninitialized_copy_n(C++11)
uninitialized_fill
uninitialized_fill_n
raw_storage_iterator
get_temporary_buffer
return_temporary_buffer
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)
shared_ptr(C++11)
weak_ptr(C++11)
auto_ptr(obsoleta)
owner_less(C++11)
enable_shared_from_this(C++11)
bad_weak_ptr(C++11)
default_delete(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.
declare_reachable(C++11)
undeclare_reachable(C++11)
declare_no_pointers(C++11)
undeclare_no_pointers(C++11)
pointer_safety(C++11)
get_pointer_safety(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.
pointer_traits(C++11)
addressof(C++11)
align(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::shared_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.
shared_ptr::shared_ptr
shared_ptr::~shared_ptr
shared_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.
shared_ptr::reset
shared_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.
shared_ptr::get
shared_ptr::operator*
shared_ptr::operator->
shared_ptr::use_count
shared_ptr::unique
shared_ptr::operator bool
shared_ptr::owner_before
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.
std::swap
make_shared
allocate_shared
static_pointer_cast
dynamic_pointer_cast
const_pointer_cast
get_deleter
operator==
operator|=
operator<
operator<=
operator>
operator>=
operator<<
atomic_is_lock_free
atomic_load
atomic_load_explicit
atomic_store
atomic_store_explicit
atomic_exchange
atomic_exchange_explicit
atomic_compare_exchange_weak
atomic_compare_exchange_strong
atomic_compare_exchange_weak_explicit
atomic_compare_exchange_strong_explicit
std::hash
 
constexpr shared_ptr();
(1)
template< class Y >
explicit shared_ptr( Y* ptr );
(2)
template< class Y, class Deleter >
shared_ptr( Y* ptr, Deleter d );
(3)
template< class Y, class Deleter, class Alloc >
shared_ptr( Y* ptr, Deleter d, Alloc alloc );
(4)
constexpr shared_ptr( std::nullptr_t );
(5)
template< class Deleter >
shared_ptr( std::nullptr_t, Deleter d );
(6)
template< class Deleter, class Alloc >
shared_ptr( std::nullptr_t, Deleter d, Alloc alloc );
(7)
template< class Y >
shared_ptr( const shared_ptr<Y>& r, T *ptr );
(8)
shared_ptr( const shared_ptr& r );
(9)
template< class Y >
shared_ptr( const shared_ptr<Y>& r );
(9)
shared_ptr( shared_ptr&& r );
(10)
template< class Y >
shared_ptr( shared_ptr<Y>&& r );
(10)
template< class Y >
explicit shared_ptr( const std::weak_ptr<Y>& r );
(11)
template< class Y >
shared_ptr( std::auto_ptr<Y>&& r );
(12)
template< class Y, class Deleter >
shared_ptr( std::unique_ptr<Y,Deleter>&& r );
(13)
Constrói shared_ptr novo a partir de uma variedade de tipos de ponteiro que se referem a um objecto de gerir. Opcional deleter d pode ser fornecido, que é depois usado para destruir o objeto quando não há objetos shared_ptr ele próprio. Por padrão, a expressão é usada como excluir expressão deleter. delete expressão adequada correspondente ao tipo fornecido é sempre selecionada, essa é a razão pela qual os construtores são implementados como modelos usando um Y parâmetro separado.
Original:
Constructs new shared_ptr from a variety of pointer types that refer to an object to manage. Optional deleter d can be supplied, which is later used to destroy the object when no shared_ptr objects own it. By default, excluir expressão expression is used as deleter. Proper delete expression corresponding to the supplied type is always selected, this is the reason why the constructors are implemented as templates using a separate parameter Y.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Se o objeto apontado por ptr já pertence a algum ponteiro compartilhada, os resultados do construtor em um comportamento indefinido.
Original:
If the object pointed to by ptr is already owned by some shared pointer, the constructor results in undefined behavior.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
1)
Construtor padrão constrói uma shared_ptr sem objeto gerenciado, ou seja shared_ptr vazio
Original:
Default constructor constructs a shared_ptr with no managed object, i.e. empty shared_ptr
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2-4)
Constrói um shared_ptr com ptr como objeto gerenciado. Y deve ser um tipo completo e implicitamente conversível para T. Além disso:
Original:
Constructs a shared_ptr with ptr as the managed object. Y must be a complete type and implicitly convertible to T. Additionally:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Usa a expressão excluir como deleter. Uma expressão de exclusão válido deve estar disponível, ou seja, delete ptr deve ser bem formado, ter um comportamento bem definido e não lançar quaisquer exceções.
Original:
Uses the delete expression as the deleter. A valid delete expression must be available, i.e. delete ptr must be well formed, have well-defined behavior and not throw any exceptions.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
Usa o d deleter especificado como o deleter. Deleter deve ser exigível para o tipo T, ou seja d(ptr) deve ser bem formado, ter um comportamento bem definido e não lançar quaisquer exceções. Deleter deve ser CopyConstructible.
Original:
Uses the specified deleter d as the deleter. Deleter must be callable for the type T, i.e. d(ptr) must be well formed, have well-defined behavior and not throw any exceptions. Deleter must be CopyConstructible.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
4)
O mesmo que (3), mas adicionalmente, usa uma cópia de alloc para a atribuição de dados para uso interno. Alloc deve ser um Allocator. O construtor de cópia e destruidor não deve lançar exceções.
Original:
Same as (3), but additionally uses a copy of alloc for allocation of data for internal use. Alloc must be a Allocator. The copy constructor and destructor must not throw exceptions.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
5-7)
Análoga a (2), (3), (4), respectivamente, mas constrói uma shared_ptr sem objecto gerido, ie vazio shared_ptr.
Original:
Analogous to (2), (3), (4) respectively, but constructs a shared_ptr with no managed object, i.e. empty shared_ptr.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
8)
Constrói um shared_ptr que compartilha informações de propriedade com r, mas tem um ptr ponteiro alheios e não gerenciados. Mesmo se este shared_ptr é o último do grupo a sair do escopo, ele irá chamar o destruidor do objeto originalmente gerida por r. No entanto, chamar get() sobre este irá sempre retornar uma cópia do ptr. É responsabilidade do programador para garantir que este ptr permanece válido, desde que este shared_ptr existe, como nos casos de uso típicos onde ptr é um membro do objeto gerenciado por r ou é um apelido (por exemplo, abatido) de r.get()
Original:
Constructs a shared_ptr which shares ownership information with r, but holds an unrelated and unmanaged pointer ptr. Even if this shared_ptr is the last of the group to go out of scope, it will call the destructor for the object originally managed by r. However, calling get() on this will always return a copy of ptr. It is the responsibility of the programmer to make sure that this ptr remains valid as long as this shared_ptr exists, such as in the typical use cases where ptr is a member of the object managed by r or is an alias (e.g., downcast) of r.get()
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
9)
Constrói um shared_ptr que compartilha a propriedade do objeto gerenciado pelo r. Se r gere nenhum objeto, *this gere nenhum objeto também. A sobrecarga de modelo não participar na resolução de sobrecarga se Y* não é implicitamente conversível para T*.
Original:
Constructs a shared_ptr which shares ownership of the object managed by r. If r manages no object, *this manages no object too. The templated overload doesn't participate in the overload resolution if Y* is not implicitly convertible to T*.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
10)
Move-constrói uma shared_ptr de r. Após a construção, *this contém uma cópia do estado anterior do r, r está vazio. A sobrecarga de modelo não participar na resolução de sobrecarga se Y* não é implicitamente conversível para T*.
Original:
Move-constructs a shared_ptr from r. After the construction, *this contains a copy of the previous state of r, r is empty. The templated overload doesn't participate in the overload resolution if Y* is not implicitly convertible to T*.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
11)
Constrói um shared_ptr que compartilha a propriedade do objeto gerenciado pelo r. Y* deve ser conversível T*. Note-se que r.lock() podem ser utilizados para o mesmo fim: a diferença é que este construtor gera uma exceção se o argumento estiver vazia, enquanto std::weak_ptr<T>::lock() constrói uma std::shared_ptr vazio nesse caso.
Original:
Constructs a shared_ptr which shares ownership of the object managed by r. Y* must be convertible to T*. Note that r.lock() may be used for the same purpose: the difference is that this constructor throws an exception if the argument is empty, while std::weak_ptr<T>::lock() constructs an empty std::shared_ptr in that case.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
12)
Constrói um shared_ptr que armazena e possui o objeto anteriormente detida pela r. Y* deve ser conversível T*. Após a construção, r está vazia.
Original:
Constructs a shared_ptr that stores and owns the object formerly owned by r. Y* must be convertible to T*. After construction, r is empty.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
13)
Constrói um shared_ptr que gerencia o objeto atualmente gerenciado por r. O deleter associado a r é armazenado para exclusão futuro do objeto gerenciado. r gere nenhum objeto após a chamada. Y* deve ser conversível T*.
Original:
Constructs a shared_ptr which manages the object currently managed by r. The deleter associated to r is stored for future deletion of the managed object. r manages no object after the call. Y* must be convertible to T*.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Índice

[editar] Notas

Ao construir a partir de um ponteiro-prima para um objeto de um tipo derivado de std::enable_shared_from_this, os construtores de shared_ptr detectar outros proprietários do objeto através da referência fraca armazenado nessa classe base acionária e com eles, em vez de assumir que o objeto não é gerenciado.
Original:
When constructing from a raw pointer to an object of a type derived from std::enable_shared_from_this, the constructors of shared_ptr detect other owners of the object through the weak reference stored in that base class and share ownership with them, instead of assuming that the object is not managed.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Parâmetros

ptr -
um apontador para um objecto de gerir
Original:
a pointer to an object to manage
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
d -
uma deleter usar para destruir o objeto
Original:
a deleter to use to destroy the object
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
alloc -
um alocador de usar para alocações de dados para uso interno
Original:
an allocator to use for allocations of data for internal use
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
r -
outro ponteiro inteligente de compartilhar a posse ou aquisição da propriedade de
Original:
another smart pointer to share the ownership to or acquire the ownership from
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Exceções

1)
noexcept specification:  
noexcept
  (a partir do C++ 11)
2)
std::bad_alloc se a memória adicional exigida não poderia ser obtida. Pode lançar implementação exceção definida para outros erros. delete ptr é chamado se ocorrer uma exceção.
Original:
std::bad_alloc if required additional memory could not be obtained. May throw implementation-defined exception for other errors. delete ptr is called if an exception occurs.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3-4)
std::bad_alloc se a memória adicional exigida não poderia ser obtida. Pode lançar implementação exceção definida para outros erros. d(ptr) é chamado se ocorrer uma exceção.
Original:
std::bad_alloc if required additional memory could not be obtained. May throw implementation-defined exception for other errors. d(ptr) is called if an exception occurs.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
5)
noexcept specification:  
noexcept
  (a partir do C++ 11)
6-7)
std::bad_alloc se a memória adicional exigida não poderia ser obtida. Pode lançar implementação exceção definida para outros erros. Se uma exceção é lançada, d(ptr) é executado.
Original:
std::bad_alloc if required additional memory could not be obtained. May throw implementation-defined exception for other errors. If an exception is thrown, d(ptr) is executed.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
8-10)
noexcept specification:  
noexcept
  (a partir do C++ 11)
11)
std::bad_weak_ptr se r.expired == true. O construtor não tem nenhum efeito neste caso.
Original:
std::bad_weak_ptr if r.expired == true. The constructor has no effect in this case.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
12)
std::bad_alloc se a memória adicional exigida não poderia ser obtida. Pode lançar implementação exceção definida para outros erros. Esse construtor não tem efeito se ocorrer uma exceção.
Original:
std::bad_alloc if required additional memory could not be obtained. May throw implementation-defined exception for other errors. This constructor has no effect if an exception occurs.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
13)
Se uma exceção é lançada, o construtor não tem efeitos.
Original:
If an exception is thrown, the constructor has no effects.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Exemplo

#include <memory>
#include <iostream>
 
struct Foo {
    Foo() { std::cout << "Foo...\n"; }
    ~Foo() { std::cout << "~Foo...\n"; }
};
 
struct D { 
    void operator()(Foo* p) const {
        std::cout << "Call delete for Foo object...\n";
        delete p;
    }
};
 
int main()
{	
    // constructor with no managed object
    std::shared_ptr<Foo> sh1;
 
    // constructor with object
    std::shared_ptr<Foo> sh2(new Foo);
    std::shared_ptr<Foo> sh3(sh2);
    std::cout << sh2.use_count() << '\n';
    std::cout << sh3.use_count() << '\n';
 
    //constructor with object and deleter
    std::shared_ptr<Foo> sh4(new Foo, D());
}

Output:

Foo...
2
2
Foo...
Call delete for Foo object...
~Foo...
~Foo...

[editar] Veja também

cria um ponteiro comum que gere um novo objeto
Original:
creates a shared pointer that manages a new object
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]
cria um ponteiro comum que gere um novo objeto alocado utilizando um alocador
Original:
creates a shared pointer that manages a new object allocated using an allocator
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]