株式会社エス・スリー・フォー

STL Samples : <memory>

アロケータ

classallocator

source

#include <iostream>
#include <memory>
#define PRINT_CTOR_DTOR
#include "foo.h"

using namespace std;

void std_alloc() {
  allocator<Foo> a;
  const int N = 5;
  cout << "allocate" << endl;
  Foo* p = a.allocate(N,0);
  int i;

  cout << "construct" << endl;
  Foo* q = p;
  for ( i = 0; i < N; ++i ) {
    a.construct(q, Foo(i));
    ++q;
  }

  cout << "print" << endl;
  q = p;
  for ( i = 0; i < N; ++i ) {
    cout << *q;
    ++q;
  }
  cout << endl;

  cout << "destroy" << endl;
  q = p;
  for ( i = 0; i < N; ++i ) {
     a.destroy(q);
     ++q;
  } 

  cout << "deallocate" << endl;
  a.deallocate(p,N);
}

テンポラリ領域

classraw_storage_iterator

fuctionget_temporary_buffer fuctionreturn_temporary_buffer

fuctionuninitialized_copy fuctionuninitialized_fill fuctionuninitialized_fill_n

source

#include <iostream>
#include <memory>
#define PRINT_CTOR_DTOR
#include "foo.h"

using namespace std;

/* Visual C++ では、get_temporary_bufferのプロトタイプは以下のとおり:
 *
 * template<class T>
 *    pair<T*, ptrdiff_t> get_temporary_buffer(ptrdiff_t n, T*);
 */

void std_storage() {
  cout << "get_temporary_buffer, return_temporary_buffer, " << endl
       << "uninitialized_copy, uninitialized_fill, uninitialized_fill_n" << endl;
  const int N = 5;
  cout << "allocate" << endl;
  Foo* p;
  pair<Foo*,ptrdiff_t> x = get_temporary_buffer(N,p);
  p = x.first;
  int i;
  Foo* q = p;

  cout << "fill" << endl;
  uninitialized_fill(p, p+N, Foo(0));

  cout << "fill again" << endl;
  uninitialized_fill_n(p, N, Foo(1));

  cout << "genarate Foo(0), Foo(1) ..." << endl;
  raw_storage_iterator<Foo*,Foo> it(p);
  for ( i = 0; i < N; ++i ) {
    *it = Foo(i);
    ++it;
  }

  pair<Foo*,ptrdiff_t> y = get_temporary_buffer(N,p);
  cout << "copy" << endl;
  uninitialized_copy(p, p+N, y.first);  

  cout << "print" << endl;
  q = y.first;
  for ( i = 0; i < N; ++i ) {
    cout << *q;
    ++q;
  }
  cout << endl;

  cout << "deallocate withour destruction" << endl;
  return_temporary_buffer(p);
  return_temporary_buffer(y.first);
}

auto_ptr

classauto_ptr

source

#include <iostream>
#include <memory>
#define PRINT_CTOR_DTOR
#include "foo.h"

using namespace std;

void std_auto_ptr_sub1(auto_ptr<Foo> ap) {
  cout << "sub1 ... ";
  ap->printOn(cout);
  cout << endl;
}

void std_auto_ptr_sub2(const auto_ptr<Foo>& ap) {
  cout << "sub1 ... ";
  ap->printOn(cout);
  cout << endl;
}

void std_auto_ptr() {
  cout << "auto_ptr" << endl;

  auto_ptr<Foo> p1(new Foo(1));
  cout << "call sub1" << endl;
  std_auto_ptr_sub1(p1);
  cout << "return from sub1" << endl;
  
  auto_ptr<Foo> p2(new Foo(2));
  cout << "call sub2" << endl;
  std_auto_ptr_sub2(p2);
  cout << "return from sub2" << endl;

  auto_ptr<Foo> p3;
  p3 = p2;
}