Namespaces
Variants

std::weak_ptr<T>:: lock

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)
std:: shared_ptr < T > lock ( ) const noexcept ;
(depuis C++11)

Crée un nouveau std::shared_ptr qui partage la propriété de l'objet géré. S'il n'y a pas d'objet géré, c'est-à-dire si * this est vide, alors le shared_ptr retourné est également vide.

Retourne effectivement expired ( ) ? shared_ptr < T > ( ) : shared_ptr < T > ( * this ) , exécuté atomiquement.

Table des matières

Valeur de retour

Un shared_ptr qui partage la propriété de l'objet possédé si std::weak_ptr::expired renvoie false . Sinon, retourne un shared_ptr construit par défaut de type T .

Notes

Cette fonction et le constructeur de std::shared_ptr peuvent être utilisés pour acquérir temporairement la propriété de l'objet géré référencé par un std::weak_ptr . La différence est que le constructeur de std::shared_ptr lance une exception lorsque son argument std::weak_ptr est vide, tandis que std::weak_ptr<T>::lock() construit un std::shared_ptr<T> vide.

Exemple

#include <iostream>
#include <memory>
void observe(std::weak_ptr<int> weak)
{
    if (auto p = weak.lock())
        std::cout << "\tobserve() is able to lock weak_ptr<>, value=" << *p << '\n';
    else
        std::cout << "\tobserve() is unable to lock weak_ptr<>\n";
}
int main()
{
    std::weak_ptr<int> weak;
    std::cout << "weak_ptr<> is not yet initialized\n";
    observe(weak);
    {
        auto shared = std::make_shared<int>(42);
        weak = shared;
        std::cout << "weak_ptr<> is initialized with shared_ptr\n";
        observe(weak);
    }
    std::cout << "shared_ptr<> has been destructed due to scope exit\n";
    observe(weak);
}

Sortie :

weak_ptr<> is not yet initialized
        observe() is unable to lock weak_ptr<>
weak_ptr<> is initialized with shared_ptr
        observe() is able to lock weak_ptr<>, value=42
shared_ptr<> has been destructed due to scope exit
        observe() is unable to lock weak_ptr<>

Rapports de défauts

Les rapports de défauts modifiant le comportement suivants ont été appliqués rétroactivement aux normes C++ précédemment publiées.

DR S'applique à Comportement tel que publié Comportement corrigé
LWG 2316 C++11 lock() n'était pas requis d'être atomique, mais requis d'être noexcept, ce qui menait à une contradiction spécifié comme étant atomique

Voir aussi

vérifie si l'objet référencé a déjà été supprimé
(fonction membre publique)