Stl map <char *, char *> destructor
3 answers
When a is map<char*,char*>destroyed, all its elements are contained. Each element destructor is called if it has a class type.
, . , - . . . delete .
:
map<char*, char*> strings;
char* key = new char[10];
char* value = new char[256];
/* ... */
strings.insert(key,value);
, delete , new, , strings .
, , new delete. map<string,string>, , .
EDIT:
@sbi, , map<string,string> over map<char*,char*>, , map<string,string> -, -.
:
#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";
}
, "foo", . , , . , , :
#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";
}
... , .
+14
, std::map<string, string> std::map<char*, char*>. , /.
, , value value . , , . . , . , .
:
class ABCD
{
public:
ABCD(const int ab) : a(ab)
{cout << "Constructing ABC object with value : " << a << endl;}
~ABCD()
{cout << "Destructing ABC object with value : "<< a << endl;}
void Print()
{ cout << "Value is : " << a << endl;}
private:
int a;
};
Consider a code that uses the smart pointer of the specified class:
{
std::map<_tstring, std::shared_ptr<ABCD>> myMap;
_tstring key(_T("Key1"));
myMap.insert(std::make_pair(key, std::make_shared<ABCD>(10)));
auto itr = myMap.find(key);
itr->second->Print();
myMap[key] = std::make_shared<ABCD>(20);
itr = myMap.find(key);
itr->second->Print();
} // myMap object is destroyed, which also calls the destructor of ABCD class
Code output above:
Constructing ABC object with value : 10
Value is : 10
Constructing ABC object with value : 20
Destructing ABC object with value : 10
Value is : 20
Destructing ABC object with value : 20
+1