mercredi 23 août 2023

Adding a weak_ptr scenario

I am trying to come up with a simple example of when a shared_ptr would be used and when a unique or a weak pointer will be used. Trying to better understand smart pointers. In my case. I came up with a Recipe scenario. A recipe will have ingredients(eggs,meat) which it will own(unique_ptr) and then a recipe is passed to a burner. The same recipe can be cooked on multiple burners (hence) a shared_ptr. This shows the basic

class Recipe {
public:
    std::vector<std::unique_ptr> ingrediants;
    void addIngrediant(std::unique_ptr<Ingrediants> i){
        ingrediants.push_back(std::move(i));
    }
};

class Burner {
public:
   std::vector<std::shared_ptr<Recipe>> recipes;
   void addRecipe(const std::shared_ptr<Recipe>& r) {
    recipes.emplace_back(r);
   }
}

In the above case I have managed to use a shared_ptr and a unique_ptr. Can someone help me come up with a situation and add a scenario on when I would use a weak_ptr ?

Aucun commentaire:

Enregistrer un commentaire