0

I have a map of objects and I copied one object to the local variable and then delete the object in the map. Could this create a problem when I work on local object?

std::map<int, obj>::iterator it2 = mymap.find(objnum);
mylocalobj = it2->second;
mymap.erase(it2);
//continue working on mylocalobj 
Avb Avb
  • 545
  • 2
  • 13
  • 25

1 Answers1

1

Copy is the key word here, if you've copied the object in the map, then what happens to the original no longer matters, unless you haven't implemented copying semantics correctly in your obj class.

If you haven't done this then you should regard your code as bugged.

john
  • 85,011
  • 4
  • 57
  • 81
  • what should I consider in order to copy correctly including semantics? – Avb Avb Sep 25 '13 at 12:25
  • It depends on your class, sometimes you don't need to do anything. Usually the key question is does your class have a destructor? If so then you need to implement the copy constructor and assignment operator for your class correctly. You could google for the 'rule of three' for more detailed help. – john Sep 25 '13 at 12:28
  • This link for instance http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three – john Sep 25 '13 at 12:30
  • my object is a struct defined as typedef struct { uint16_t length; uint8_t *data; } obj; In this case, do I need an additional assignment operator? – Avb Avb Sep 25 '13 at 12:40
  • Do you allocate memory and assign it to `data`? – john Sep 25 '13 at 12:48
  • yes I did it in the local object. myData = new uint8_t[1000]; mylocalobj.data = myData; – Avb Avb Sep 25 '13 at 12:49
  • The issue is that when you copy `obj` you will end up with two `data` pointers pointing at the same memory. Who's responsible for deleting that memory? If you get that wrong your program is likely to crash. It sounds like you are making things hard for yourself and the program would be simpler if you did implement a destructor, copy constructor and assignment operator. But it's your code so I can't say for sure what you should do. – john Sep 25 '13 at 12:53