Jump to content
  • Advertisement
Sign in to follow this  
baker

simple question on Maps and inserting objects into them

This topic is 4488 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
ok thanks.

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!