Home > front end >  Why can't use a inside pointer to initialize two difference shared_ptr?
Why can't use a inside pointer to initialize two difference shared_ptr?

Time:08-21

#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?

CodePudding user response:

shared_ptr<Base> p(q);
shared_ptr<Base> t(q);

p and t now both have sole ownership of *q instead of sharing the ownership.

p and t do not share control blocks for *q. Whenever por t reaches a reference count of zero, *q will be destructed - and the other shared_ptr will be left with a dangling reference.

Any references to the former object after its destruction results in undefined behavior.


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

Because C relies on you to do it properly - but it doesn't do much to prevent you from violating the rules.

  • Related