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 such that i can delete my food instance in a single place. it would 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 the dynamic_cast doesn't seem to work with weak_ptr
how do I get a weak_ptr<Fruit>
out of a weak_ptr<Food>
if i know that the object it points to is of derived type?
Direct casting from weak_ptr<A>
to weak_ptr<B>
will surely don't work, I think you have to convert it to a shared_ptr
and then use the casting functionality of shared_ptr:
weak_ptr<Food> food = myFoodFactory->createFood(eFruit)
weak_ptr<Fruit> fruit = weak_ptr<Fruit>(dynamic_pointer_cast<Fruit>(food.lock());
You cannot use dynamic_cast
with shared_ptr
because it would require to change the template of the object. What in fact you want to do is a dynamic_cast
on the internal pointer. To do this you could do a dynamic_cast
on the pointer returned by get
but that would not be so clean because the reference would not be shared(irrelevant in your case since you're using weak_ptr
but relevant when using shared_ptr
) and creating a share_ptr on this would be undefined resulting on a double delete.
Use dynamic_pointer_cast
to do this but the two types still need to be related. In other words dynamic_cast<T*>(r.get())
needs to be well formed.
you can use BOOST_DISABLE_THREADS to improve performance if you're not bound to multithreading, see https://stackoverflow.com/a/8966130/1067933
精彩评论