samedi 2 juin 2018

Destruction of each other in c++ shared_ptr

everyone. I find a problem in c++ deconstruction. I will show you my code below:

#include <iostream>
#include <memory>
#include <vector>

using namespace std;

class B;

class A{
public:
    typedef shared_ptr<A> Ptr;

    shared_ptr<B> b;

    int index;

    A(const shared_ptr<B>& b_, int index_):b(b_), index(index_){}

    ~A(){cout << "A is deleted." << endl;
         cout << "A id is " << index << endl;}



};

class B{
public:
    typedef shared_ptr<B> Ptr;

    vector<A::Ptr> all_a;

    void addA(){
        for(int i=0; i<10; i++){
            auto a = make_shared<A>(Ptr(this), i);

            all_a.push_back(a);
        }

    }

    int index;

    B(int index_):index(index_){

    }

    ~B(){
        cout << "B is deleted." << endl;
        cout << "B id is " << index << endl;
    }


};



int main(){

    B::Ptr b = make_shared<B>(5);

    b->addA();

    return 0;
}

A part of results is is

... B is deleted. B id is 5 A is deleted. A id is 8 B is deleted. B id is 5 A is deleted. A id is 9 B is deleted. B id is 5 double free or corruption (out) [1] 29094 abort (core dumped) ./a.out

What is it happened with my code, how can i debug this problem. I thought the shared_ptr has some bug in this case.

Aucun commentaire:

Enregistrer un commentaire