jebsector
October 3rd, 2011, 01:01 AM
I have a function that returns a reference to an object that is created within the method as follows:
(class myItems)
boost::shared_ptr<item> anItem::getItem(int32 a) {
boost::shared_ptr<item> anItem(new item());
...
anItem->a = struct[spot]->a;
anItem->b = struct[spot]->b;
return anItem;
}
The following code results in a segfault as I'm assuming the method getItem has anItem go out of scope before returning it, and destroys the object. It happens exactly as getItem returns:
myItems a; ...
boost::shared_ptr<item> foundI = a->getItem(0);
My question is, how can I return anItem from getItem, with maintaining a valid reference to the internal function variable and thereby returning that to the caller? I know I can use a class member but I want to avoid that if possible..
(class myItems)
boost::shared_ptr<item> anItem::getItem(int32 a) {
boost::shared_ptr<item> anItem(new item());
...
anItem->a = struct[spot]->a;
anItem->b = struct[spot]->b;
return anItem;
}
The following code results in a segfault as I'm assuming the method getItem has anItem go out of scope before returning it, and destroys the object. It happens exactly as getItem returns:
myItems a; ...
boost::shared_ptr<item> foundI = a->getItem(0);
My question is, how can I return anItem from getItem, with maintaining a valid reference to the internal function variable and thereby returning that to the caller? I know I can use a class member but I want to avoid that if possible..