I am having a lil hard time with map and the valuetype allocation.
consider this simple class:
class Column {
private:
char *m_Name;
public:
// Overrides
const char *Name(){
return this->m_Name;
}
// Ctors
Column(const char *NewName){
this->m_Name = new char[strlen(NewName) + 1];
strcpy(this->m_Name, NewName);
}
// Dtors
~Column(){
cout << "wtf?\n";
delete this->m_Name;
}
};
now I have this map:
// Typedefs
typedef std::map<int, Column> ColumnContainer;
ColumnContainer *m_Container;
When i call this:
Column *c = new Column("Test");
cout << "CREATED: " << c->Name() << "\n";
it = this->m_Container->insert(std::make_pair(0, *c)).first;
cout << "AGAIN: " << c->Name() << "\n";
the console is printing the “wtf?” after the insert in the map.
it seems to be destroying the column. Is this right?
or am I doing something wrong?
I was wondering if the value_type of the std::map has to a struct type with defined memory size, like with POD or array of POD?
the cout << AGAIN
doesn’t print the “Test”
what I need is a map to a columns based on int key
The underlying reason why your string m_Name doesn’t print the second time is because of the way the STL builds a map. It makes various copies of the value during its insertion. Because of this, m_Name gets destroyed in one of the copies of the original column.
Another piece of advice is to use pointers to objects when the object is a value in the map. Otherwise you could be taking a major performance hit of the object is large enough.