class A
{
public:
A(int i)
{
x = new int(i);
}
~A()
{
if (x != NULL)
{
delete x;
x = NULL;
}
}
private:
A();
int *x;
};
void f()
{
{
map<int,A> myMap;
A a(2);
// myMap[7] = a; // cannot access default ctor
pair<int, A> p(7,a);
myMap.insert(p);
}
}
The problem here is that upon scope exit the destructor of A is called twice. Probably the first time to destruct A a(2) and the 2nd time to destruct some temp object created by map. This causes an exception since x is not allocated.
- Why does the command
myMap[7] = aconstruct a newAand why does it use the default ctor? - What can be a solution?
operator=, you should also declare move constructor.