I would like to model a group of items (people) where each individual has a set of unique characteristics... If I pass around my objects willy-nilly then copy constructors, etc. will cause my objects to diverge such that Object A will eventually have multiple different versions floating around, A` returned from method X, A`` returned from method Y and so forth. Which design pattern will help me ensure that if I pass around objects to various functions, that I'll be sure to always be acting on the unique representation of each given object. Thanks.
Asked
Active
Viewed 70 times
0
-
4Just pass around smart pointers. 'nuff said – Luchian Grigore Jan 17 '13 at 16:26
-
You can protect classes against being copied and enforce pointer/reference semantics, as mentioned. Note also the existence of the convenience class [boost::noncopyable](http://stackoverflow.com/questions/7823990/what-are-the-advantages-of-boostnoncopyable) – HostileFork says dont trust SE Jan 17 '13 at 16:31
3 Answers
2
Either use smart pointers or just pass by reference. I'm not really sure what more advanced design pattern you're expecting to need.

djechlin
- 59,258
- 35
- 162
- 290
2
As others have said, pointers, smart pointers, or pass-by-reference.
If you're worried about forgetting, you can make the copy constructor private. That way, passing by value will be a compiler error.

dspeyer
- 2,904
- 1
- 18
- 24
2
Just don't make copies of your objects. Store them all in a central location (using a container like std::vector or std::unordered_map) and then pass references to your various functions. For example:
void MutatePerson( Person& object );
void InspectPerson( const Person& object );

Peter Ruderman
- 12,241
- 1
- 36
- 58