how to get stl map to construct/destruct inserted object only once.

Posted by Alberto Toglia on Stack Overflow See other posts from Stack Overflow or by Alberto Toglia
Published on 2010-06-06T16:40:59Z Indexed on 2010/06/06 16:52 UTC
Read the original article Hit count: 153

Filed under:
|

I have found a very prejudicial fact about stl maps. For some reason I cant get objects being inserted in the map to get constructed/destructed only once.

Example:

struct MyObject{
    MyObject(){
        cout << "constructor" << endl;
    }
    ~MyObject(){
        cout << "destructor" << endl;
    }
};
int main() {
    std::map<int, MyObject> myObjectsMap;
    myObjectsMap[0] = MyObject();
    return 0;
}

returns:

constructor
destructor
destructor
constructor
destructor

If I do:

typedef std::pair<int, MyObject> MyObjectPair;
myObjectsMap.insert( MyObjectPair(0,MyObject()));

returns:

constructor
destructor
destructor
destructor

I'm inserting Objects responsible for their own memory allocation, so when destructed they'll clean themselves up, being destructed several times is causing me some trouble.

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl