My question revolves around whether or not I must expose my use of the boost::shared_ptr from my interface and whether or not I should expose raw pointers or references from my interface.
Consider the case of a Person who has an Employeer. Employeer internally maintains all of its employees in a vector< shared_ptr< Person > >. Because of this, do best practices dictate that any interface involving Person should be a shared_ptr wrapped person?
For example, are all or only some of these ok:
Person Employeer::getPresidentCopy();
Person& Employeer::getPresidentRef();
Person* Employeer::getPresidentRawPtr();
shared_ptr<Person> Employeer::getPresidentSharedPtr();
Or for example:
void Employeer::hireByCopy(Person p);
void Employeer::hireByRef(Person& p);
void Employeer::hireByRawPtr(Person* p);
void Employeer::hireBySharedPtr(shared_ptr<Person> p);
If I later want to change the implementation to use johns_very_own_shared_ptr instead of the boost variety, am I trapped in the old implementation?
On the other hand, if I expose raw pointers or references from the interface, do I risk someone deleting the memory out from under the shared_ptr? Or do I risk the shared_ptr being deleted and making my reference invalid?
See my new question for an example involving this.
It depends on what you’re trying to accomplish. Why does the vector hold
shared_ptrs instead of just directly storingPersons by value? (And have you consideredboost::ptr_vector?)You should also consider that maybe what you really ought to hand out is a
weak_ptr.Pretty much, but it’s not impossible to fix. (I suspect that in C++0x, liberal use of the
autokeyword will make this easier to deal with, since you won’t have to modify the calling code as much, even if it didn’t usetypedefs.) But then, why would you ever want to do that?Yes, but that’s not your problem. People can extract a raw pointer from a
shared_ptranddeleteit, too. But if you want to avoid making things needlessly unsafe, don’t return raw pointers here. References are much better because nobody ever figures they’re supposed todelete &reference_received_from_api;. (I hope so, anyway ^^;;;; )