vendredi 12 août 2022

Smart pointers still refers to raw pointer even though reset is applied

Please find the code attached which I took from https://www.geeksforgeeks.org/auto_ptr-unique_ptr-shared_ptr-weak_ptr-2/ for testing the

// C++ program to demonstrate shared_ptr
#include <iostream>
#include <memory>

class A {
public:
    void show()
    {
        std::cout << "A::show()" << std::endl;
    }
};

int main()
{
    std::shared_ptr<A> p1(new A);
    std::cout << p1.get() << std::endl;
    p1->show();
    std::shared_ptr<A> p2(p1);
    p2->show();
    std::cout << p1.get() << std::endl;
    std::cout << p2.get() << std::endl;

    // Returns the number of shared_ptr objects
    // referring to the same managed object.
    std::cout << p1.use_count() << std::endl;
    std::cout << p2.use_count() << std::endl;

    // Relinquishes ownership of p1 on the object
    // and pointer becomes NULL
    p1.reset();
    std::cout << p1.get() << std::endl;
    std::cout << p2.use_count() << std::endl;
    std::cout << p2.get() << std::endl;
    p1->show();
    p2->show();
    std::cout << p1.get() << std::endl;
    std::cout << p2.use_count() << std::endl;
    std::cout << p2.get() << std::endl;

    return 0;
}

p1 is reset and no pointer is assigned to it (Found as per p1.get()). After that, When I am calling p1->show() function, it shows the output as A::show(). How it is possible?

output:
0x24dc5ef1790
A::show()
A::show()
0x24dc5ef1790
0x24dc5ef1790
2
2
0
1
0x24dc5ef1790
A::show() 
A::show()
0
1
0x24dc5ef1790

Aucun commentaire:

Enregistrer un commentaire