关于析构函数
  • 板块学术版
  • 楼主cjwdyzxfblzs
  • 当前回复21
  • 已保存回复21
  • 发布时间2023/10/8 09:36
  • 上次更新2023/11/2 14:57:45
查看原帖
关于析构函数
817044
cjwdyzxfblzs楼主2023/10/8 09:36

在写树状数组的时候发现了一个这样的问题。

在我里面的变量类型是vector的时候

struct BIT {
    int n, ts;
    std::vector<int> c, vis;
    BIT() {}
    BIT(int n) : n(n), c(n + 1), vis(n + 1) {}
    void upd(int x, int k) {
        for (; x <= n; x += x & -x) {
            if (vis[x] != ts) vis[x] = ts, c[x] = 0;
            c[x] += k;
        }
    }
    int qry(int x) {
        int ans = 0;
        for (; x ; x -= x & -x) ans += vis[x] == ts ? c[x] : 0;
        return ans;
    }
    void clear(){ts ++ ;}
    ~BIT() {
        std::cout << "<- [succeed running ~BIT] ->" << std::endl;
    }
}tree[2];

我是这样进行调用的构造函数

tree[0] = BIT(sz + 1), tree[1] = BIT(sz + 10);

因为这样子调用构造函数,这个 BIT(sz+1) BIT(sz + 1) 用完了会销毁自动调用了我的析构函数2次。我是理解的。

然后在这个 treetree 变量退出的时候也调用了两次,我感觉也没什么问题。

但是在我将vector用int*替换了之后就不一样了。

struct BIT {
    int n, ts;
    int *c, *vis;
    BIT() {}
    BIT(int sz) {
        n = sz;
        c = new int[sz]();
        vis = new int[sz]();
    }
    void upd(int x, int k) {
        for (; x <= n; x += x & -x) {
            if (vis[x] != ts) vis[x] = ts, c[x] = 0;
            c[x] += k;
        }
    }
    int qry(int x) {
        int ans = 0;
        for (; x ; x -= x & -x) ans += vis[x] == ts ? c[x] : 0;
        return ans;
    }
    void clear(){ts ++ ;}
    ~BIT() {
        std::cout << "<- [succeed running ~BIT] ->" << std::endl;
        delete c;
        delete vis;
    }
}tree[2];

在我使用指针调用的时候,treetree 变量只调用了一次析构函数。这让我很不理解。

为什么这个析构函数只调用了一次啊????

2023/10/8 09:36
加载中...