Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Création et Utilisation des Pointeurs Faibles | Pointeurs Faibles
Pointeurs Intelligents C++

book
Création et Utilisation des Pointeurs Faibles

Création de Weak Pointers

Vous devriez généralement créer un std::weak_ptr à partir d'un std::shared_ptr existant. Cela garantit que le weak pointer observe un objet déjà géré par au moins un shared pointer.

h

creating_weak_pointer

copy
std::shared_ptr<int> p_shared = std::make_shared<int>(42);
std::weak_ptr<int> p_weak(sharedPtr);
12
std::shared_ptr<int> p_shared = std::make_shared<int>(42); std::weak_ptr<int> p_weak(sharedPtr);

Le std::weak_ptr p_weak est construit à partir d'un std::shared_ptr existant p_shared. Cela signifie que p_weak n'augmente pas le compteur de référence de p_shared mais observe plutôt le même objet géré. La validité de p_weak dépend de p_shared; si toutes les instances de std::shared_ptr gérant l'objet sont détruites, p_weak expire et ne peut plus être utilisé pour accéder directement à l'objet.

Utilisation des pointeurs faibles

Pour accéder à un objet géré par un std::weak_ptr, vous devez d'abord le convertir en un std::shared_ptr en utilisant lock(). Cette méthode vérifie si l'objet est toujours vivant et renvoie un std::shared_ptr vers celui-ci, sinon, elle renvoie un std::shared_ptr vide.

Verrouiller un pointeur faible empêche l'objet d'être détruit pendant son utilisation. Étant donné que std::weak_ptr ne contribue pas au compteur de références, accéder directement à l'objet risquerait d'utiliser une instance détruite. Le convertir en un std::shared_ptr augmente le compteur de références, garantissant que l'objet reste valide pendant son utilisation.

h

converting

copy
auto locked_shared = p_weak.lock();
if (locked_shared)
// The object is alive, and you can use lockedSharedPtr to access it.
else
// The object has been deallocated, and lockedSharedPtr is empty.
12345
auto locked_shared = p_weak.lock(); if (locked_shared) // The object is alive, and you can use lockedSharedPtr to access it. else // The object has been deallocated, and lockedSharedPtr is empty.
Tâche

Swipe to start coding

Complétez le code suivant pour créer un std::weak_ptr à partir d'un std::shared_ptr, le convertir de nouveau en un std::shared_ptr, et accéder en toute sécurité à la valeur de l'objet géré.

Solution

cpp

solution

#include <iostream>
#include <memory>
#include <string>

int main()
{
std::shared_ptr<std::string> p_shared_string = std::make_shared<std::string>("Hello, World!");

// Create a weak pointer from the shared pointer
std::weak_ptr<std::string> p_weak_string(p_shared_string);

// Convert the weak pointer to a shared pointer to access the string
std::shared_ptr<std::string> p_another_shared_string = p_weak_string.lock();

// Check if the shared pointer is valid before accessing the string
if (p_another_shared_string)
// Print the value of the string
std::cout << *p_another_shared_string << std::endl;
else
std::cout << "The string has already been deleted." << std::endl;
}
Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 4. Chapitre 2
#include <iostream>
#include <memory>
#include <string>

int main()
{
// Assuming you have a shared pointer to a string
std::shared_ptr<std::string> p_shared_string = std::make_shared<std::string>("Hello, World!");

// Create a weak pointer from the shared pointer
___::___<std::string> p_weak_string = ___ ;

// Convert the weak pointer to a shared pointer to access the string
std::___<std::string> p_another_shared_string = ___;

// Check if the shared pointer is valid before accessing the string
if (___)
// Print the value of the string
std::cout << *___ << std::endl;
else
std::cout << "The string has already been deleted." << std::endl;
}
toggle bottom row
We use cookies to make your experience better!
some-alt