Search code examples
c++c++11shared-ptrsmart-pointers

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?


Solution

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

    Yes.

    After "P2=P1" the memory allocated to P1 has to be deallocated right?

    No. It could happen to P2 if it pointed to something. Not P1.

    The logic behind the rule (2) is that the assignment overwrites the value of the first operand, so the first operand will no longer point to what it used to. If it was the last pointer to something, then nothing will point to that anymore, and it can be deleted.