C++ std::sort() 调用析构函数

标签 c++

我重载了我的类的() 运算符以将其用作排序比较器函数。使用 std::sort() 时,出于某种原因,它多次调用类的析构函数(显然取决于 vector 中的条目数量)。我在 ~RANK() 中描述了更多内容。

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>

class RANK
{
    struct COMBO
    {
        int x;
    };

    std::vector<COMBO *> data;
public:
    RANK()
    {
        printf("RANK()\n");
    }

    ~RANK()
    {
        printf("~RANK()\n");

        /*
         * Here is the problem.
         * Since my vector consists of pointers to COMBO objects,
         * I delete them upon RANK object's destruction. However,
         * std::sort() calls RANK's destructor many times and
         * throws some runtime error, unless commented out.
         */
        //for (unsigned int i = 0, n = data.size(); i < n; i++)
        //  delete data[i];
    }

    void Add(int x)
    {
        COMBO *combo = new COMBO();
        combo->x = x;

        data.push_back(combo);
    }

    unsigned int Size()
    {
        return data.size();
    }

    void Sort()
    {
        std::sort(data.begin(), data.end(), *this);
    }

    int operator[](unsigned int pos)
    {
        return data[pos]->x;
    }

    bool operator()(COMBO *combo1, COMBO *combo2)
    {
        return combo1->x > combo2->x;
    }
};

int main()
{
    RANK rank;
    rank.Add(1337);
    rank.Add(9001);
    rank.Sort();

    for (unsigned int i = 0, n = rank.Size(); i < n; i++)
        printf("%d ", rank[i]);
        printf("\n");

    system("pause");

    return 0;
}

输出(带注释的析构函数):

RANK()
~RANK()
~RANK()
~RANK()
~RANK()
~RANK()
9001 1337

最佳答案

std::sort 的比较函数是按值传递的。通过使用 RANK 对象作为比较器,您将向 std::sort 传递一个拷贝(作为最后一个值),它可能会在内部多次复制它。

我建议将 COMBO 的比较运算符从类 RANK 中分离出来

关于C++ std::sort() 调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13384576/

相关文章:

用于检查字符串是否平衡 ()、{} 和 [] 的 C++ 程序

c++ - QT qmake 小写我的自定义小部件名称

c++ - 如何在 win32 中获取窗口的直接子项(不是任何孙子项)?

c++ - 使用 ifstream 处理制表符并将任意数量的值读入 vector

c++ - Qt QGraphicsview 如何 Hook 调整事件大小

c++ - Qt,QFile写在特定的行

C++ - 希望虚拟仅作为重定向

c++ - std::bind 与类型别名

c++ - 静态变量的地址值可以与堆分配地址匹配吗?

c++ - 基类函数不调用派生类函数