Bart wrote:
> Hi all,
>
> I'm trying to figure something out for quite a while now.
> Say a class A has a stl map containing instances of class A. The
> "uniqueness" of the elements in the map is just a string. I want this
> map to be available to every instance of A so I make it static. After
> a lot of trying this leads to two questions from my side:
>
> -- are there any mistakes/newbie errors in the approach above?
Only a trap: that map will be shared amongst all instances of class A.
Should your program ever use threads, you will need to properly protect that
static map from being modified in one thread and accessed in any way from
another. There is a design decision to be made, which you will read in the
last paragraph of this post.
> -- How would you implement such a thing.
What you need (if I understood you well) is that all the constructors add
the new instance to the map. For that you will need at least one mandatory
argument for all constructors: the string, which is the key of your map.
The destructor would of course take the "record" out of the map. Meaning
that constructors would add the value of "this" to the static
map<std::string, A*> member and destructors delete it. To find out how to
use map make a Google search for "stl tutorial". Try to find one which is
fairly recent and seems to come from a good source. Google even seems to
have a category for STL tutorials at
http://directory.google.com/Top/Comp...utorials/?il=1
As it seems that your instances of class A are uniquely identified (you talk
about map and not multimap) there will be a bit of a trouble with
implementing a copy constructor. Depending on what does really your class
represent you will either not implement one (meaning you will disable it by
making its signature private) or you will implement it, but it will not
touch the key, only the "data" part. Same for the copy assigment operator.
This is IMHO an important part of the problem: to decide if these object can
be copied in any way or not. It is clear that since a map is chosen there
can be no two (or more) object sharing the same key, so the previously
mentioned decision has to be made.
--
WW aka Attila