Variable organisation problem
Ive got two classes A and B.
A is a standalone class, B requires a pointer to A when its constructed, which cant be changed (refrence counting is used so an A instance is never destroyed if instances of B created "with" it still exist).
B needs to store some information (for example a counter), for each instance of A used to create it (eg to go with the counter example, lets say the number of B instances created with that A instance).
The problem is how to store this counter variable.
I could add the variable to class A, and make B a friend so it has access to it, however A doesnt really need to know anything about B, so I dont want to add anything like this to A.
The other option I considered was giving B a static map variable, so it can store infomation on each A instance, eg "std::map<A*,unsigned> counters;", however this seems untidy because ive now got a varaible which is kinda linked to every A instance, but not actaully a member of A. Also I imagen that as the number of diffrent A instances that have existed and been used to create B instance, performance will degrade due to the map lookup B has to keep doing...
Which of these two implementations is best, and do I have any further options?
Why do you need to do this? Perhaps with a bit of re-organisation you could avoid this problem?
I think you should take a look at boost::shared_ptr. Give each B instance a shared_ptr to the A instance they need. The shared_ptr will do the reference counting - and cleaning up - for you.
Will each B class only reference one A class? If so why not store a pointer to A inside B so that if you need anything from A withing B you can just call A's methods to get what you need.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement