Espacios de nombres
Variantes
Acciones

std::shared_ptr::shared_ptr

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

 
 
Utilidades de la biblioteca
Escriba apoyo (basic types, RTTI, type traits)
Gestión de memoria dinámica
Gestión de errores
Programa de servicios públicos
Funciones variadic
Fecha y hora
Objetos Function
initializer_list(C++11)
bitset
hash(C++11)
Operadores relacionales
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 y 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)
Cambiar, hacia adelante y mover
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)
 
Gestión de memoria dinámica
Bajo la gestión de memoria de nivel
Los asignadores
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)
Inicializar el almacenamiento
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
Punteros 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(obsoleto)
owner_less(C++11)
enable_shared_from_this(C++11)
bad_weak_ptr(C++11)
default_delete(C++11)
Garbage soporte colección
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)
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.
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
Las funciones miembro
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
Los 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
Terceros funciones
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)
Construye shared_ptr nuevo a partir de una variedad de tipos de puntero que se refieren a un objeto de manejar. Opcional Deleter d se pueden suministrar, que luego se utiliza para destruir el objeto cuando no hay objetos shared_ptr pertenece. De forma predeterminada, la expresión se utiliza como suprimir la expresión Deleter. delete expresión adecuado correspondiente al tipo suministrado siempre se selecciona, esta es la razón por la que los constructores se implementan como plantillas usando un parámetro separado .. Y
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, suprimir la expresión 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.
Si el objeto al que apunta ptr ya es propiedad de algún puntero compartida, los resultados de constructor en el comportamiento no definido .
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)
Constructor por defecto construye un shared_ptr sin objeto administrado, es decir shared_ptr vacía
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)
Construye un shared_ptr con ptr como el objeto administrado. Y debe ser un tipo completo e implícitamente convertible a T. Además:
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)
Utiliza la expresión delete como Deleter. Una expresión delete válida debe estar disponible, delete ptr es decir, debe estar bien formados, tienen un comportamiento bien definido y no lanzar ninguna excepción .
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)
Utiliza el especificado d Deleter Deleter como el. Deleter debe ser exigible para el tipo T, es decir d(ptr) deben estar bien formados, tienen un comportamiento bien definido y no lanzar ninguna excepción. Deleter debe 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)
Igual que (3), pero, además, utiliza una copia del alloc para la asignación de datos para uso interno. Alloc debe ser un Allocator. El constructor de copia y el destructor no deben producir excepciones .
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, pero construye un shared_ptr sin objeto gestionado, es decir, vacío 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)
Construye un shared_ptr que comparte información sobre la propiedad con r, pero tiene un puntero ptr sin relación y no administrado. Incluso si esta shared_ptr es el último del grupo para salir de su ámbito, se llamará al destructor del objeto originalmente administrado por r. Sin embargo, llamar get() en esta siempre devolverá una copia de ptr. Es la responsabilidad del programador, para asegurarse de que esta ptr sigue siendo válido siempre y cuando este shared_ptr existe, tal como en los casos de uso típicos donde ptr es un miembro del objeto gestionado por r o es un alias (por ejemplo, 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)
Construye un shared_ptr que comparte una propiedad del objeto administrado por r. Si r administra ningún objeto, ningún objeto *this gestiona también. La sobrecarga plantilla no participa en la resolución de sobrecarga Y* si no es implícitamente convertible a 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-construye un shared_ptr de r. Después de la construcción, *this contiene una copia del estado anterior de r, r está vacía. La sobrecarga plantilla no participa en la resolución de sobrecarga Y* si no es implícitamente convertible a 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)
Construye un shared_ptr que comparte una propiedad del objeto administrado por r. Y* debe ser convertible a T*. Tenga en cuenta que r.lock() puede ser utilizado para el mismo propósito: la diferencia es que este constructor lanza una excepción si el argumento está vacío, mientras que std::weak_ptr<T>::lock() construye un std::shared_ptr vacío en ese 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)
Construye un shared_ptr que almacena y posee el objeto anteriormente propiedad de r. Y* debe ser convertible a T*. Después de la construcción, r está vacío .
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)
Construye un shared_ptr que administra el objeto actualmente gestionado por r. El Deleter asociado a r se almacena para su eliminación futura del objeto administrado. r administra ningún objeto después de la llamada. Y* debe ser convertible a 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.

Contenido

[editar] Notas

Cuando se construye a partir de un puntero sin formato a un objeto de un tipo derivado de std::enable_shared_from_this, los constructores de shared_ptr detectar otros propietarios del objeto a través de la referencia débil almacenado en esa clase de base y propiedad de las acciones con ellos, en lugar de asumir que el objeto no se gestiona .
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 -
un puntero a un objeto de manejar
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 -
Deleter una utilizar para destruir el 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 -
un asignador a utilizar para la asignación de datos 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 -
otro puntero inteligente para compartir la titularidad o adquisición de la titularidad 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] Excepciones

1)
noexcept specification:  
noexcept
  (desde C++11)
2)
std::bad_alloc si la memoria adicional requerida no se pudo obtener. Puede lanzar la aplicación definida por excepción para otros errores. delete ptr se llama si se produce una excepción .
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 si la memoria adicional requerida no se pudo obtener. Puede lanzar la aplicación definida por excepción para otros errores. d(ptr) se llama si se produce una excepción .
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
  (desde C++11)
6-7)
std::bad_alloc si la memoria adicional requerida no se pudo obtener. Puede lanzar la aplicación definida por excepción para otros errores. Si se produce una excepción, d(ptr) se ejecuta .
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
  (desde C++11)
11)
std::bad_weak_ptr si r.expired == true. El constructor no tiene ningún efecto en este 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 si la memoria adicional requerida no se pudo obtener. Puede lanzar la aplicación definida por excepción para otros errores. Este constructor no tiene efecto si se produce una excepción .
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)
Si se produce una excepción, el constructor no tiene efectos .
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] Ejemplo

#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] Ver también

crea un puntero compartido que gestiona un nuevo 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.

(función de plantilla) [edit]
crea un puntero compartido que gestiona un nuevo objeto asignado usando un asignador
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.

(función de plantilla) [edit]