Re: how can operator new overrun memory?!
Dear Christian
How on earth does new overwrite memory? I don't ever supply the new
operator with memory to step on!
Here is the code:
// static function
Token* Token::getInstance(Slot* slot) {
printf("%s\n",__FUNCTION__);
Token* me = NULL;
map<Slot*,Token*>::iterator itr = tokens.find(slot);
if(itr != tokens.end())
me = itr->second;
else {
me = new Token(slot);
tokens[slot] = me;
}
return me;
}
Looking at your code - which I do not flaw - I have two (?useless) thoughts.
I wondered if I could ask why you did not let the map class manage the
memory allocation for the Tokens and removed a layer of indirection. I would
have written
map<Slot*,Token>::iterator itr = tokens.find(slot);
if(itr != tokens.end())
{
return & itr->second;
}
else
{
return & (tokens[slot] = slot);
};
Perhaps my code, through the implicit
slot -> Token(slot)
and copy into tokens[slot]
would result in an unneccesary construction destruction pair when compared
with yours; although I might hope that the compiler is clever enough to
build the temporary variable in the correct place.
I know another good reason not to embed the tokens in the map class. They
will all get destroyed when the instance of the class containing the map
class "tokens" goes out of scope. Often this is a very good thing, but there
are times when this is really not what you want. Some of the "new" objects
may need to have a persistence across compilation units.
If this second reason is close to your reason then, as you mention dlls, you
are in a context similar to one where I experienced things going wrong with
new and delete.
new or delete 'ing a Token calls the allocator or deallocator linked to the
compilation unit where the new or delete happened. The beginning and end of
the instance can be in different units. In my case, the runtime libraries
etc. linked into the code were not consistent across these different
modules. This lead to inconsistency between the allocator used in the new
and the destructor used in the delete and caused a real mess.
Doubt if anything I have said is useful for your problem and I am sure the
penultimate paragraph is obvious to you. Best regards anyhow.
Terry
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]