Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 455
Alexander Avatar asked Apr 06 '12 19:04

Alexander


People also ask

What is boost shared_ptr?

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.

What does shared_ptr get () do?

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.

What is shared_ptr?

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.

What is boost :: Make_shared?

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.


1 Answers

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.

like image 197
Kerrek SB Avatar answered Sep 23 '22 00:09

Kerrek SB