Boost shared_ptr operator =

Here is a sample code

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 output 0?

Documentation note: Effects: equivalent to shared_ptr (r) .swap (* this).

But if the objects shared_ptrjust swap, the result should be 9. And if the first object is deleted, there must be a segmentation error.

So why 0?

+5
source share
4 answers

Pay particular attention to what is being replaced:

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

, r. , , . spi *spi, , pi->f() - undefined.

+6

pi . - undefined; 0, .

+5

, 0?

, !

spi , . pi , . pi->f() - undefined .

+1

pithe object is deleted after spi = spi2and who knows what your runtime does for the freed memory. For me, it prints -572662307 in Debug and 1315904 in Release.

+1
source

All Articles