Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map, references, pointers and memory allocation

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

like image 408
Jonathan Avatar asked Dec 06 '22 04:12

Jonathan


1 Answers

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.

like image 58
Éric Malenfant Avatar answered Dec 07 '22 18:12

Éric Malenfant