Josh S wrote:
I have a few newb questions:
I have the following classes
class Base { Base(); virtual ~Base(); virtual doStuff(); }
class Foo: public Base { doStuff(); }
class FooContainer { createFoos(int numOfFoos); Foo* getFoo(int indexToFoo); Destroy(); }
class BaseContainer { void addObj(boost::shared_ptr<Base> obj); }
How do I cast the pointer returned from FooContainer::getFoo(), as something I can pass to BaseContainer::addObj ? Is this correct to do this? Assuming I cant change the implementation of FooContainer or the BaseContainer interface. The BaseContainer interface should not have a special case for adding Foo's.
Good practise tells me I shouldn't create a temporary either.
I do not want the shared_ptr in BaseContainer to call delete on Foo (I will manually call FooContainer::Destroy()
If you can be certain that the Foo objects will outlive their shared pointers (i.e. no shared_ptr<Foo> will ever be accessed after FooContainer::Destroy() has been called), you can create shared_ptrs for Foos with a 'null deleter', which will prevent the shared_ptr from deleting the object when its use_count hits zero. Go to http://www.boost.org/libs/smart_ptr/sp_techniques.html#static for an example of this technique.
Now, what happens if I instead want FooContainer to only be responsible for creating the Foo objects, and not be responsible for deleting them. Instead I want the shared_ptr to call delete when the objects reference count reaches 0. How would that done?
If you can be certain that FooContainer won't try to delete the objects itself or pass them to another piece of code that might and that no raw Foo pointer will be used to initialize more than one shared Foo pointer, then you can safely create regular shared_ptrs from the Foo pointers. Just be aware that in either case, "be certain" means more than just, "I know going to write it that way." It should also mean, "I know that five years from now when someone modifies my code, they won't be tempted to screw this up." If neither of these solutions are right for you, you might try browsing the entire page that I referenced earlier (http://www.boost.org/libs/smart_ptr/sp_techniques.html). It's full of great tips for using shared pointers in tricky situations. If there's a good solution to your problem, you'll probably find it there. HTH, Beth