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?
shared_ptr is now part of the C++11 Standard, as std::shared_ptr . Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. This is accomplished by using an array type ( T[] or T[N] ) as the template parameter.
A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.
The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.
The header file <boost/make_shared. hpp> provides a family of overloaded function templates, make_shared and allocate_shared , to address this need. make_shared uses the global operator new to allocate memory, whereas allocate_shared uses an user-supplied allocator, allowing finer control.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With