Atouk
Atouk

Reputation: 53

Delete a pointer as first key of std::map

I was wondering how to properly delete a pointer which is the first key of a std::map. I can only figure this out for the second key. The first key is only readable.

Example:

std::map<char*,foo> myMap;
char* str = new char[3];
foo bar;
str[0]='h';
str[1]='i';
str[2]='\0';
myMap[str] = bar

/* some code */
for(auto element: myMap)
{
    delete [] element.first;
}

This doesn't seem to free the pointer. Did std::map lose the pointer somewhere? I am working on big data, so I need string structures as light as possible. That's why I worked with char* and not std::string (with a comparator functor given to the map).

EDIT

For more precisions:

I hope this help you to understand my question.

Upvotes: 1

Views: 698

Answers (3)

Atouk
Atouk

Reputation: 53

Resolved

Thank you all, loads of your comments help to solve my problem. I succeed in using std::string. I know, i told you that it was too weight. But I found the méthod reserve(size_t n=0) which allow exactly the place we want to. Now, there is no leak anymore.

Thanks again for your answers!

Sources: http://www.cplusplus.com/reference/string/string/reserve/

Upvotes: 0

erol yeniaras
erol yeniaras

Reputation: 3797

Your map has two elements and you need to delete the first: it->first is a char* and it->second is a foo. Try the following code:

for(std::map<char*, foo>::iterator it = myMap.begin(); it!=myMap.end(); it++)
{
     delete[] it->first;
     myMap.erase(it);
}

Hope that helps!

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106086

Your code already works (but isn't exception safe - a smart pointer would be). Note that when memory is deleted, the program doesn't normally waste time changing it, it just changes some free/in-use records so a future allocation can consider that memory for reuse, so if you try to dereference the deleted pointers you have undefined behaviour but it might seem to still have the old contents - at least for a while. I assume that's why you think the deallocation isn't working....

Upvotes: 1

Related Questions