I know that a map destructor calls each of the contained element's destructors. What happens for a
map<char*,char*> ?
I cannot see where this code is in /usr/include/c++/4.4
EDIT: I should have said
map<const char*, const char*, ltstr>
like in
http://www.sgi.com/tech/stl/Map.html
To check if a key exists in a C++ map, you can use std::map::count. It returns 0 (the key is absent) or 1 (the key is present).
By default, a Map in C++ is sorted in increasing order based on its key.
When a map<char*,char*>
is destroyed, so are all of the elements it contains. Each element's destructor is called, if it is of class type.
However, keep in mind exactly what is contained in your map above. It isn't strings, as you might expect -- it's just pointers to strings. The strings themselves aren't destroyed. Only the pointers are. delete
is never called on the pointers.
Case in point:
map<char*, char*> strings;
char* key = new char[10];
char* value = new char[256];
/* ... */
strings.insert(key,value);
In the above, since delete
is never called on the pointers created by the calls to new
, this memory will leak when strings
goes out of scope.
This is a good illustration of why you should avoid using raw pointers, new
and delete
. In your case, map<string,string>
would probably be a better choice.
EDIT:
As @sbi mentioned in the comments, another reason why you would want map<string,string>
over map<char*,char*>
is because with map<string,string>
keys are compared by-value, rather than by-pointer-value.
Consider:
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main()
{
static const char MyKey[] = "foo";
const char bar[] = "bar";
typedef map<const char*,const char*> Strings;
Strings strings;
strings.insert(make_pair(MyKey,bar));
string ss = "foo";
Strings::const_iterator it = strings.find(ss.c_str());
if( it == strings.end() )
cout << "Not Found!";
else
cout << "Found";
}
Fundamentally, you're inserting an element with the key "foo" and then searching for that element. Test the above code, and you'll find that it isn't found. If, however, you try this:
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main()
{
typedef map<string,string> Strings;
Strings strings;
strings.insert(make_pair("foo","bar"));
string ss = "foo";
Strings::iterator it = strings.find(ss);
if( it == strings.end() )
cout << "Not Found~!";
else
cout << "Found";
}
...you get the behavior you really wanted.
What happens
Nothing. If you dynamically allocated memory, it'll leak - there's no automatic destructor for char*
.
Use std::string
or similar class instead.
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