Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

c++ - 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?

question from:https://stackoverflow.com/questions/65641658/how-memory-is-deallocated-in-shared-ptr-via-the-operator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...