simple question on Maps and inserting objects into them
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?
Quote:Original post by bakerThat will work, I think, but there's no particular reason to do it that way. The following would be more efficient and straightforward:
map<int, mytype> myMap;
main{
mytype *obj1 = new mytype;
myMap[1] = *obj1;
delete obj1;
}
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.
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
CM
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement