# simple question on Maps and inserting objects into them

## Recommended Posts

baker    158
Hi, I have a question. class mytype { string dataString; member functions.... } map<int, mytype> myMap; main{ mytype *obj1 = new mytype; myMap[1] = *obj1; delete obj1; } ////////////////////////////////////// now does "myMap[1] = obj1;" copy all the contents of what obj1 is pointing at into some other memory that can be accessed by myMap? is the delete correct? thanks. btw: does this belong into the beginners forum?

##### Share on other sites
jyk    2094
Quote:
 Original post by bakermap myMap;main{ mytype *obj1 = new mytype; myMap[1] = *obj1; delete obj1;}
That will work, I think, but there's no particular reason to do it that way. The following would be more efficient and straightforward:
myMap[1] = mytype();
Quote:
 btw: does this belong into the beginners forum?
Perhaps. Don't get me wrong, pointers and memory management in C++ is not a particularly easy topic. Like it or not though, an understanding of the subject is more or less a prerequisite for any non-trivial C++ work.

##### Share on other sites
baker    158
thanks jyk.

more annoying questions,

what easiest/cleaner/safer?

map<int, myobject> mydata;

vs

map<int, myobject *> mydata;

if i do the second way, whatever myobject pointer is pointing to, must be declared a "new myobject" so it stays in allocated memory right?

if i do it the first way, when i insert the object into mydata, it stays there.

##### Share on other sites
Conner McCloud    1135
Don't store pointers unless you need to. In this case, you clearly don't or else you wouldn't be asking if you should. Store the actual object, the library is smart enough to treat it right.

CM

##### Share on other sites
baker    158
ok thanks.

im reading some c++ books now. all these things that i thought i knew i actually didnt.