jeudi 15 juillet 2021

Move semantic of shared_ptr

I just started learning smart pointer and came across a situation which seems to be contradicting with the theory. For e.g. When we use shared_ptr and if copy semantic is called the both the object shares the ownership and ref count is 2. This is okay and understood. code for example.

 class Test {
    public:
    Test(){ cout << "Const" << "\n"; }

    void Disp(){
        cout << "Class Test()\n";
    }

    ~Test(){ cout << "Dest" << "\n"; }
 };

int main()
{
 Test *p = new Test();
 shared_ptr<Test> p1(p);
 shared_ptr<Test> p2(p1); // = make_shared<Test>(*p1);

 p1->Disp();
 p2->Disp();

}

And output is fine as :

Const
Class Test()
Class Test()
Dest

Now if I try move semantic as

int main()
{
 Test *p = new Test();
 shared_ptr<Test> p1(p);
 shared_ptr<Test> p2 = make_shared<Test>(*p1);

 p1->Disp();
 p2->Disp();

}

Then p1 should have lost the ownership. Hence p1->Disp() should be valid. Because make_shared will transfer ownership as well as reset the p1. But still I can call p1->Disp() and the proper function is getting called. Please correct my understanding.

Thanks.

Aucun commentaire:

Enregistrer un commentaire