dimanche 29 juillet 2018

C++ why raw pointer won't increase reference count of shared_ptr?

the shared_ptr use reference count to determine when to destroy the object. And pls look at this code:

int main() {
    std::shared_ptr<int> pt = std::make_shared<int>(3);
    int *pt2 = pt.get();
    cout << "reference count " << pt.use_count() << endl;
    pt = 0;
    cout << *pt2;

};

after I set pt to 0, the reference count should become 0, and the object should be destroyed. But I can still use pt2 to access it. In my case, the result is correct, but I guess it's just luck. So does it mean that the reference count mechanism still can not make it 100% safe if the programmer want to do some stupid thing?

Aucun commentaire:

Enregistrer un commentaire