【发布时间】:2019-07-01 11:14:50
【问题描述】:
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);
}
}
这里的问题是,在范围退出时,A 的析构函数被调用了两次。可能是第一次破坏A a(2),第二次破坏map创建的一些临时对象。这会导致异常,因为 x 未分配。
- 为什么命令
myMap[7] = a会构造一个新的A,为什么它使用默认的ctor? - 有什么解决办法?
【问题讨论】:
-
你必须声明复制构造函数,
operator=,你也应该声明移动构造函数。 -
你看过this thread吗?
标签: c++