0

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.

ChaimKut
  • 2,759
  • 3
  • 38
  • 64

3 Answers3

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