Search code examples
c++boostshared-ptr

boost shared_ptr operator =


Here is code example

class A{
  int i;
public:
  A(int i) : i(i) {}
  void f() { prn(i); }
};

int main()
{
  A* pi = new A(9);
  A* pi2= new A(87);
  boost::shared_ptr<A> spi(pi);
  boost::shared_ptr<A> spi2(pi2);
  spi=spi2;
  spi->f();
  spi2->f();
  pi->f();
  pi2->f();
}

output:

87
87
0
87

The question is why is 0 in the output?

Note from documentation: Effects: Equivalent to shared_ptr(r).swap(*this).

But if shared_ptr objects just swapped, the result should be 9. And if the first object is deleted, there should be Segmentation fault.

So why 0?


Solution

  • Pay careful attention to what is being swapped:

    shared_ptr(r).swap(*this)
    // ^^^^^^^^^^
    

    That's a temporary object constructed from r. The temporary goes out of scope immediately and dies, with whichever effects this has on the owned resource. Since in your code spi was the only owner of *spi, the object is deleted, and your subsequent access of pi->f() is simply undefined behaviour.