vendredi 19 août 2022

Why can't use a inside pointer to initialize two difference shared_ptr?

#include<iostream>
#include<memory>
using namespace std;

class Base;

class Base {
public:
    int i;
    int j;
    Base(int _i, int _j) : i(_i), j(_j) {};
};

int main(void) {
    Base* q = new Base(5, 9);
    cout << q->i << endl;
    shared_ptr<Base> p(q);
    cout << p->j << endl;
    shared_ptr<Base> t(q);            // mark
    cout << p.use_count() << endl;
    // cout << t.use_count() << endl;
    return 0;
}

After I run it on visual studio 2022 with C++11, the reference count is 1 rather than two, and there's something wrong with delete that makes the programme failed.

However, when I change the code marked into "shared_ptr t(p)", everything goes well.

How?

Aucun commentaire:

Enregistrer un commentaire