Sign in to follow this  
baker

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


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


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


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this