【发布时间】:2013-06-24 18:26:09
【问题描述】:
在下面的代码中,析构函数被多次调用:-
#include<iostream>
#include<map>
using namespace std;
class abc{
public:
abc()
{
cout<<"\nconstructor called\n";
}
~abc()
{
cout<<"\ndestructor called\n";
}
void fun()
{
cout<<"\nfunction called\n";
}
};
struct cmp_str
{
bool operator()(abc a,abc b)
{
return 1;
}
};
int main()
{
map<abc,int,cmp_str> mymap;
abc a;
mymap[a]=5; // destructor is called twice
//mymap.insert(pair<abc,int>(a,5)); // // destructor is called 3 times
map<abc,int,cmp_str>::iterator it=mymap.begin();
mymap.clear();
while(1)
{
//infinite loop added to check number of times destrctor is called before objects goes out of scope
}
return 1;
}
我正在使用不同的方式在对象中插入值。 一个使用 insert() 函数,另一个使用简单的 []。 当我使用 mymap[a]=5 插入时;然后析构函数被调用两次,而当我评论这一行并使用 insert() 函数进行插入时,析构函数被调用三次。 由于 mymap.clear() 可以忽略一个析构函数,但为什么要调用其余的析构函数。
我在 return 上方插入了无限循环,这样我就可以忽略当对象超出范围时调用的析构函数。 请帮助我理解这种行为,因为多次调用析构函数是危险的,如果处理不当可能会导致核心转储。
【问题讨论】:
-
当您使用
insert()时,还有一个,因为调用该函数时会涉及到一个复制构造函数。 -
@AlexandruBarbarosie:实际上,我相信我们正在看到被破坏的是临时
pair对象中的对象。
标签: c++ c++11 map destructor