I want a map to hold an object and be responsible for its deletion either when the map comes out of scope or explicitly when 'erase' is called for one of its member objects.
using std::court;
struct A {
int x;
char y;
A(int z,char c): x(z),y(c){}
~A() { cout<<"destructor x:"<<x<<std::endl;}
};
int main() {
std::map<int,A> m;
std::pair<std::map<int,A>::iterator,bool> ret;
cout<<"Hello start"<<std::endl;
char c='f';
ret=m.insert(std::pair<int,A>(5,A(8,c)));
if (ret.second) {
cout<<"Element inserted"<<std::endl;
if (m.erase(5)==1)
cout<<"Element erased"<<std::endl;
}
return 0;
}
However, the above code will call the destructor for A several times. Clearly a lot of copying is taken place with temporary variables that are going out of scope. There must be a more efficient way. I consider using emplace like
m.emplace(5,8,c);
But that is not possible since emplace for map only takes two parameters. What am I doing wrong?