I’m trying to write a copy constructor for an object managing a STL map containing pointers, where the key is a string. However, when I attempt to insert new values in the map, the pointers are set to NULL:
// ...
for(std::map<std::string, data_base*, order>::const_iterator it = other.elements.begin();
it != other.elements.end(); ++it){
data_base *t = it->second->clone();
std::cout << "CLONE: " << std::hex << t << std::endl;
elements[it->first] = t;
std::cout << "INSERTED: " << std::hex << elements[it->first] << std::endl;
}
// ...
other is the object being copied and elements the map. The clone() method returns a pointer to a new object (via new).
Running the code above I get something like:
CLONE: 0xcfbbc0
INSERTED: 0
I’m not a very experienced programmer and this issue is probably simple to fix, but I didnt find any solution to it searching around.
Thanks a lot for your time.
I don’t see any problem with this code, other than maybe
Here
ordergives the key comparator to use to sort the pairs contained in the map (often implemented as a tree).Maybe you’re doing something wrong in it, making your [] operator don’t find the right ke, making your last line logging a new pair with a null ptr.
First, try without that
order, using the default key-comparator (std::less), then if it don’t work, post yourorderdefinition and the map declaration. If it’s not enough, just provide a simple complete program that reproduce the problem.I just wrote a simple similar test, using the default key-comparator :
On VS2010SP1, this outputs :
So it should be the problem, or maybe you’re doing something wrong before.