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
make_pair(0, *c)
creates a (temporary, unnamed) pair<int, Column>
. This pair is passed to map::insert
by reference, and, since std::map
owns its elements, it makes a copy of the pair. Then, the temporary pair is destroyed, destroying the Column object it contains.
This is why it is necessary to properly define copy-construction for types that you want to use as standard container elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With