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?
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.
pi
has been deleted. Accessing a member of a deleted object is undefined behavior; you could get 0, some other value, or a segmentation fault.
So why 0?
So anything!
Assigning a new value to spi
will delete the previous object it is pointing to. The makes pi
a dangling pointer that cannot be used anymore. Calling pi->f()
is undefined behaviour and can have any result.
pi
object is deleted after spi = spi2
and who know what your runtime does for freed memory. For me it prints -572662307 in Debug and 1315904 in Release.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.