Re: map (associative array) loses values?
On Sep 11, 6:44 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
<jeroenv...@gmail.com> wrote in message
news:1189527328.279612.21880@19g2000hsx.googlegroups.com...
ah, ok. <string, int> works like a charm! :)
I'm using new, because I need the table somewhere else. The
try/catch is in my main, while the function resides in the
SearchText class. The delete statements are there, I just
didn't post them ;)
Ofcourse I'm just a c++ newbie (this is my first program
actually), so what would you do different?
Just because you need the map somewhere else doesn't mean you
should new it.
Maybe. The question isn't really so much where it is used, but
what its lifetime must be. In his case, for example, he can't
use a local variable, because the lifetime must extend beyond
the end of the function. If the lifetime corresponds to the
class in which it is created, he should make it a member
variable, but if nothing else has the correct lifetime, he's
pretty much stuck with using dynamic allocation; it's the means
C++ offers to achieve an arbitrary lifetime.
On the other hand, I don't think I've ever needed a standard
container with arbitrary lifetime; if he needs one, I suspect
that there is a design problem somewhere upstream.
The standard containers are actually quite small in and of
themselves. If you need the map somewhere else, you are
passing the pointer to it, correct? So just pass the pointer,
or better yet, a reference to it. Creating the map in the
function is not the best method.
That's probably correct. And of course, there's nothing wrong
per se with having the function return (a copy of) the map, as
long as the number of elements is reasonably small and the
function isn't called from the middle of a tight loop in a
critical section of code.
[...]
This is just trying to show that you don't have to new
everything, in fact, you shouldn't when you don't have to.
As a general rule, use dynamic allocation only when you need
explicitlly managed lifetime. (There are a few other cases, but
they probably don't concern a beginner.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34