Namespaces
Variants

std::weak_ptr<T>:: use_count

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
long use_count ( ) const noexcept ;
(desde C++11)

Devuelve el número de shared_ptr instancias que comparten la propiedad del objeto gestionado, o 0 si el objeto gestionado ya ha sido eliminado, es decir, * this está vacío.

Contenidos

Parámetros

(ninguno)

Valor de retorno

El número de shared_ptr instancias que comparten la propiedad del objeto gestionado en el instante de la llamada.

Notas

El uso y comportamiento de esta función son similares a std::shared_ptr::use_count , pero retorna un conteo diferente.

Ejemplo

#include <iostream>
#include <memory>
std::weak_ptr<int> gwp;
void observe_gwp()
{
    std::cout << "use_count(): " << gwp.use_count() << "\t id: ";
    if (auto sp = gwp.lock())
        std::cout << *sp << '\n';
    else
        std::cout << "??\n";
}
void share_recursively(std::shared_ptr<int> sp, int depth)
{
    observe_gwp(); // : 2 3 4
    if (1 < depth)
        share_recursively(sp, depth - 1);
    observe_gwp(); // : 4 3 2
}
int main()
{
    observe_gwp();
    {
        auto sp = std::make_shared<int>(42);
        gwp = sp;
        observe_gwp(); // : 1
        share_recursively(sp, 3); // : 2 3 4 4 3 2
        observe_gwp(); // : 1
    }
    observe_gwp(); // : 0
}

Salida:

use_count(): 0   id: ??
use_count(): 1   id: 42
use_count(): 2   id: 42
use_count(): 3   id: 42
use_count(): 4   id: 42
use_count(): 4   id: 42
use_count(): 3   id: 42
use_count(): 2   id: 42
use_count(): 1   id: 42
use_count(): 0   id: ??

Véase también

verifica si el objeto referenciado ya fue eliminado
(función miembro pública)