I’m working on a project where several different object are semantically linked together and I’m now looking for a good way to let the objects refer to each other. Usually I would put pointers in each object and link them together. In this special case there are no heap objects (at least I do not create any while writing the code, what a vector does internally might be on another page). We came up with the idea to have a class that stores a list of unique ids and share this id with the objects that need them to known.
Is this good practice? Are there other, better ways to do this?
Background: The project is settled in an academic background. We do not definitely know what students or other people contribute to this. Also the skill level is not known, but probably not very high. By not using pointers we can at least ensure that objects are not deleted accidentally or out of stupidity.
Edit:
What led me to the idea of a unique id was our usage of vectors to store the data. One thing that STL containers do a lot is copying their containees. This is why I’m not so sure that pointers would work well. Same with simple indices of the vector elements, the content and/or it’s order might change.
Is this good pratice?
In my experience, no. Any sort of unique ID crap is just one more thing that has to be managed, and managed correctly or you’ll get all kinds of weird bullshit spraying all over. I worked on a product once that used this idea and a good portion of our bugs, and even more maintenance problems, was caused by having to remember about the stupid ID tracking variable. Granted, the implementation was quite convoluted (borderline insane) and it’s very easy to do better than was being done, but it’s still just one more thing to deal with when you already have a unique ID generated by the system: the address of the variable.
Are there other, better ways to do this?
Yeah, use pointers.
Unfortunately there’s no such thing as a smart pointer (that I know of anyway) that can be used to simply refer to objects owned elsewhere so for now, you have to make sure to enforce the issue through policy and documentation. It’s a weakness, yes, but still a much better alternative to tracking and ID, which can just as easily have the same problems and more.
If you’re interested in smart pointers that can be used for such purposes you might be interested in my latest blog entry.