c++ - 插入 map 时多次调用析构函数

标签 c++ c++11 dictionary destructor

在下面的代码中,析构函数被多次调用:-

#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 上方插入了无限循环,这样我就可以忽略对象超出范围时调用的析构函数。 请帮助我理解这种行为,因为对析构函数的多次调用是危险的,如果处理不当可能会导致核心转储。

最佳答案

您的比较仿函数按值接受它的参数,因此会生成和销毁临时拷贝。

但是,由于 as-if 规则的复制省略异常(exception),很难预测将存在的临时对象的确切数量。这将取决于您的优化器有多好以及是否所有内容都被内联。

关于c++ - 插入 map 时多次调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17282381/

相关文章:

c++ - 按值传递函数(?)而不是函数指针?

c++ - 将数组的值分配给C++中另一个数组的索引

C++函数装饰器

ios - 从使用 Mirror 创建的字典中过滤 nil 值

C++ 宏文本操作

c++ - 在 Linux 上使用 CMake 时,如何告诉 PVS-Studio 忽略第三方库中的所有文件

c++ - 错误 C2664 char [80] 到 char

c++ - 使用 consteval 代替 constexpr 函数有什么优点?

ios - 如何从嵌套 JSON Swift 检索值

python - 如何通过检查最新的时间戳和值从字典列表中提取