simple question on Maps and inserting objects into them

Started by
3 comments, last by baker 18 years, 1 month ago
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?
Advertisement
Quote:Original post by baker
map<int, mytype> 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.

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.
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
ok thanks.

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

This topic is closed to new replies.

Advertisement