Boost logo

Boost Users :

From: Seweryn Habdank-Wojewódzki (shw_at_[hidden])
Date: 2007-06-22 06:02:44


Hi!

Is there any smart_ptr and ptr_container that can transfer ownership of
pointer, to avoid useless copy-construction and destruction of the object.

More less scenario can be like that.

1. smart pointer handles pointer to the huge data.
2. pointer is transfered via signal to the object that has queue of them.
2a. remark not all object are going to the queue, so there is a need to keep
them in smart pointer.
3. Queue sends away pointer, or internally destroys (respectively to demand of
another signal in the program.

More less the simplified draft is shown below.

Maybe I have to use vector <shared_ptr <T> > instead of ptr_container?

Best regards.

#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>

class Foo
{
public:
  Foo (int const i)
  : i_ (i), j_()
  {
    ++counter;
    ++crcounter;
    std::cout << "Foo (int)" << '\t';
    print_counter();
  }

  Foo (Foo const & f)
  : i_ (f.i_), j_()
  {
    ++counter;
    ++crcounter;
    std::cout << "Foo (Foo)" << '\t';
    print_counter();
  }
  
  ~Foo()
  {
    --counter;
    std::cout << "~Foo () " << '\t';
    print_counter();
  }
  
  void print (std::ostream & os) const
  {
    os << i_;
  }

  static int counter;
  static int crcounter;
  static void print_counter()
  {
    std::cout << "No. Foo = " << counter
      << " No. created = " << crcounter << '\n';
  }
private:
  int i_;
  int j_[10000];
};

int Foo::counter = 0;
int Foo::crcounter = 0;

std::ostream & operator<< (std::ostream & os, Foo const & f)
{
  f.print (os);
  return os;
}

int main()
{
  using namespace boost;
  using std::cout;

  ptr_vector<Foo> pvf;

  Foo * pf = new Foo(7);
  cout << *pf << '\n';

  pvf.push_back (pf);

  pf = new Foo(9);
  cout << *pf << '\n';

  pvf.push_back (pf);

  shared_ptr<Foo> spf (new Foo(11));
  cout << *spf << '\n';
  
  pvf.push_back (new Foo (*spf));

  spf = shared_ptr <Foo> (new Foo(13));
  cout << *spf << '\n';
  
  pvf.push_back (new Foo (*spf));

  cout << pvf[0] << '\n';
  cout << pvf[1] << '\n';
  cout << pvf[2] << '\n';
  cout << pvf[3] << '\n';

  pf = new Foo(pvf[0]);
  pvf.erase(pvf.begin());
  cout << *pf << '\n';

  spf = shared_ptr <Foo> (new Foo (pvf[2]));
  cout << *spf << '\n';

  delete pf;
}

-- 
|\/\/|   Seweryn Habdank-Wojewódzki
 \/\/

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net