samedi 9 janvier 2021

How memory is deallocated in shared_ptr via the operator=?

I am a beginner to c++, I was learning the concept of shared_ptr. I also understood that Several shared_ptr objects may own the same object and the object is destroyed and its memory deallocated when either of the following happens:

1.the last remaining shared_ptr owning the object is destroyed; 2.the last remaining shared_ptr owning the object is assigned another pointer via operator= or reset().

But when I tried to execute a sample program ``` class Rectangle { int length; int breadth;

       public: 
           Rectangle(int l, int b) 
           { 
             length = l; 
             breadth = b; 
           } 

           int area() 
           { 
               return length * breadth; 
           } 
         }; 

         int main() 
        { 

             shared_ptr<Rectangle> P1(new Rectangle(10, 5)); 
             cout << P1->area() << endl; 

             shared_ptr<Rectangle> P2; 
             P2 = P1;  //how is this possible 

            // This'll print 50 
            cout << P2->area() << endl; 

            // This'll now not give an error, 
            cout << P1->area() << endl; 
            cout << P1.use_count() << endl; 
            return 0; 
           } 
   ```

After "P2=P1" the memory allocated to P1 has to be deallocated right? But still we can print P1->area(). Please explain how this is happening?

Aucun commentaire:

Enregistrer un commentaire