I'm pretty new to the world of pointers an开发者_StackOverflow中文版d have run into a problem in my code. I have a factory class that spits out shared_ptr's. "Entity" is the base class for any type of shared_ptr that gets created from this method.
If I overwrite the pointer in the get_entity method, everything seems to work. If i overwrite the pointer in the get_pointer method it doesn't.
//
// typedef boost::shared_ptr<Entity> EntityPtr;
Entity::EntityPtr EntityFactory::get_entity(int type) {
// My default pointer if everything else falls through
Entity::EntityPtr e = boost::make_shared<Entity>(type);
std::cout << e->get_type() << std::endl; // Entity
switch (type) {
case 1:
// This works
e = boost::make_shared<TextEntity>(type);
std::cout << e->get_type() << std::endl; // TextEntity
break;
case 2:
// This doesn't work
get_pointer(e, type);
std::cout << e->get_type() << std::endl; // Entity
break;
}
return e;
}
// This function can (possibly) overwrite the passed-in pointer
void EntityFactory::get_pointer(Entity::EntityPtr e, int type) {
// ...
e = boost::make_shared<TextEntity>(type);
// ...
}
My reasons for passing "e" into the get_pointer method was because i don't always need to modify the pointer. In some cases get_pointer finishes without modifying the pointer at all.
I'm hoping someone can help shed some light on what i'm doing wrong here. Thanks!
I'm pretty darn confusuled about wtf you're trying to do since you pass in integers to make_shared.
Your problem may be solved by accepting a reference to Entity::EntityPtr
in get_pointer
.
精彩评论