删除指针矢量时避免双重免费

发布于 2025-01-30 23:53:24 字数 692 浏览 3 评论 0原文

我尝试了以下内容,但是在运行时获得了分割故障和“在TCACHE2中的双免费检测到”:

class A {
... 
};

class B {
    public:
        B(...) {...}
        ~B() {
        for(int i=0;i<As.size();i++) {
            if(As[i] != nullptr) {
                delete As[i];
                As[i] = nullptr;
                }
    
            }
        }
        std::vector<A*> As;
};

int main()
{   
    A* a1 = new A(...);
    A* a2 = new A(...);
    
    B* b1 = new B(...);
    b* b2 = new B(...);
    
    b1.As.push_back(a1);
    b1.As.push_back(a2);
    
    b2.As.push_back(a1);

    delete b1;
    delete b2;
    return 0;
}

有什么办法可以保证我只删除这些指针一次?

I have tried the following, but getting segmentation fault and "double free detected in tcache2" during runtime:

class A {
... 
};

class B {
    public:
        B(...) {...}
        ~B() {
        for(int i=0;i<As.size();i++) {
            if(As[i] != nullptr) {
                delete As[i];
                As[i] = nullptr;
                }
    
            }
        }
        std::vector<A*> As;
};

int main()
{   
    A* a1 = new A(...);
    A* a2 = new A(...);
    
    B* b1 = new B(...);
    b* b2 = new B(...);
    
    b1.As.push_back(a1);
    b1.As.push_back(a2);
    
    b2.As.push_back(a1);

    delete b1;
    delete b2;
    return 0;
}

Is there any way I could assure that I delete these pointers only once?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡墨 2025-02-06 23:53:24

好的,您正在将相同的指针存储在两个阵列中。是的,您正在删除两次。这就是为什么在现代C ++中劝阻原始指针的原因。改用智能指针。

std::unique_ptr<A> a1 = std::make_shared<A1>();

之后,您可以像其他任何指针一样使用它们,除了类型不同,您不必删除它们。他们参考计数。如果需要,只需将值设置为nullptr即可。

a1 = nullptr;  // Will free if this is the last copy.

Okay, you're storing the same pointer in two arrays. So yes, you're deleting it twice. This is why the use of raw pointers has become discouraged in modern C++. Use smart pointers instead.

std::unique_ptr<A> a1 = std::make_shared<A1>();

After that, you can use them just like any other pointer, except the type is different and you do NOT have to delete them. They reference count. Just set the value to nullptr if you want.

a1 = nullptr;  // Will free if this is the last copy.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文