C ++ boost :: shared_ptr and boost :: weak_ptr & dynamic_cast

I have something like this:

enum EFood{
    eMeat,
    eFruit
};

class Food{
};

class Meat: public Food{
    void someMeatFunction();
};

class Fruit: public Food{
    void someFruitFunction();
};

class FoodFactory{
    vector<Food*> allTheFood;
    Food* createFood(EFood foodType){
        Food* food=NULL;
        switch(foodType){
            case eMeat:
                food = new Meat();
                break;
            case eFruit:
                food = new Fruit();
                break;
        }
        if(food)
            allTheFood.push_back(food);
        return food;
    }
};

int foo(){
    Fruit* fruit = dynamic_cast<Fruit*>(myFoodFactory->createFood(eFruit));
    if(fruit)
        fruit->someFruitFunction();
}

Now I want to change my application to use boost shared_ptr and weak_ptr so that I can delete my food instance in one place. it will look like this:

class FoodFactory{
    vector<shared_ptr<Food> > allTheFood;
    weak_ptr<Food> createFood(EFood foodType){
        Food* food=NULL;
        switch(foodType){
            case eMeat:
                food = new Meat();
                break;
            case eFruit:
                food = new Fruit();
                break;
        }

        shared_ptr<Food> ptr(food);
        allTheFood.push_back(ptr);
        return weak_ptr<Food>(ptr);
    }
};

int foo(){
    weak_ptr<Fruit> fruit = dynamic_cast<weak_ptr<Fruit> >(myFoodFactory->createFood(eFruit));
    if(shared_ptr<Fruit> fruitPtr = fruit.lock())
        fruitPtr->someFruitFunction();
}

but the problem is that dynamic_cast does not work with weak_ptr

How can I get weak_ptr<Fruit>from weak_ptr<Food>if I know that the object it points to is of a derived type?

+3
source share
3 answers

Direct casting from weak_ptr<A>to weak_ptr<B>will certainly not work, I think you need to convert it to shared_ptr, and then use the shared_ptr cast functions:

weak_ptr<Food> food = myFoodFactory->createFood(eFruit)
weak_ptr<Fruit> fruit = weak_ptr<Fruit>(dynamic_pointer_cast<Fruit>(food.lock());
+3
source

dynamic_cast shared_ptr, . , , dynamic_cast . dynamic_cast , get, , ( , weak_ptr, shared_ptr), share_ptr undefined, .

dynamic_pointer_cast , . , dynamic_cast<T*>(r.get()) .

0

BOOST_DISABLE_THREADS , , . fooobar.com/questions/254896/...

0

Source: https://habr.com/ru/post/1791225/


All Articles