如何通过 operator= 在 shared_ptr 中释放内存?

How memory is deallocated in shared_ptr via the operator=?

我是c++初学者,正在学习shared_ptr的概念。 我也明白 多个 shared_ptr 对象可能拥有同一个对象,当发生以下任一情况时,该对象将被销毁并释放其内存:

1.the 最后剩余的 shared_ptr 拥有对象被销毁; 2.the 拥有对象的最后剩余 shared_ptr 通过 operator= 或 reset() 分配了另一个指针。

但是当我尝试执行示例程序时

     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; 
            } 

在“P2=P1”之后,分配给 P1 的内存必须被释放,对吗? 但我们仍然可以打印 P1->area()。 请解释这是怎么发生的?

您了解的有关销毁共享指针的知识是正确的。但在这里,你不是在破坏 P1。相反,您将 P1 分配给 P2shared_ptr 的实现有一个 overloaded copy assignment operator 允许此操作并使其正确。

通过重载实现,P2 现在是一个共享指针,指向与 P1 相同的对象 - 两个指针访问相同的对象,因此您正在打印相同的区域。它们都处于有效状态,如您所见,管理该 Rectangle 对象的指针数为 2。

定义重载 =shared_ptr 的概念一致 - 有多个指针指向(欠)同一个对象。如果您想查看对比的实现,请查找 unique_ptr - this is a smart pointer that assumes only one pointer has an ownership of the object. It also has an overloaded assignment operator,但使用它会使 P1 无效(据我所知,它会将其设置为 nullptr,因此它仍然处于有效状态状态,只是不指向任何东西)。 P2 将是 Rectangle 的唯一所有者。值得一试,加深理解。

您可以找到有关 shared_ptr 功能的更多信息 here

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

是的。

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

没有。如果它指向某物,它可能会发生在 P2 上。不是 P1.

规则 (2) 背后的逻辑是赋值会覆盖第一个操作数的值,因此第一个操作数将不再指向它原来的位置。如果它是指向某个东西的最后一个指针,那么就没有任何东西再指向那个东西,它可以被删除。