summaryrefslogtreecommitdiff
path: root/libcult/examples/mm/transfer/transfer.cxx
blob: 81014d0651721fad291ba230ce62dc6de4efc1c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// file      : examples/mm/transfer/transfer.cxx
// author    : Boris Kolpackov <boris@kolpackov.net>
// copyright : Copyright (c) 2005-2010 Boris Kolpackov
// license   : GNU GPL v2 + exceptions; see accompanying LICENSE file

#include <cult/mm/evptr.hxx>

#include <iostream>

using std::cerr;
using std::endl;

using namespace Cult;

unsigned long count = 0;
unsigned long clone_count = 0;

struct Type
{
  Type ()
  {
    ++count;
  }

  ~Type ()
  {
    --count;
  }

  Evptr<Type>
  clone () const
  {
    ++clone_count;
    return Evptr<Type> (new Type);
  }

  Void
  f () const
  {
    Int i = i_;
    ++i;
  }

  Int i_;
};


Evptr<Type>
source ()
{
  return Evptr<Type> (new Type);
}

Void
sink (Evptr<Type> a, Boolean r = true)
{
  if (r)
  {
    sink (a, false);
  }
  else
  {
    Evptr<Type> b (a);

    cerr << "\tshare count: " << b.count () << endl;

    // Any of these will trigger cloning.
    //
    b->f ();
  }
}

Int
main ()
{
  // case 1
  //
  {
    cerr << "sink (new type)" << endl;

    clone_count = 0;
    sink (new Type);

    cerr << "\tclone count: " << clone_count << endl
         << endl;
  }

  // case 2
  //
  {
    cerr << "sink (source ())" << endl;

    clone_count = 0;
    sink (source ());

    cerr << "\tclone count: " << clone_count << endl
         << endl;
  }


  // case 3
  //
  {
    cerr << "sink (p)" << endl;

    clone_count = 0;

    Evptr<Type> p (new Type);
    sink (p);

    cerr << "\tclone count: " << clone_count << endl
         << endl;
  }


  cerr << "balance: " << count << endl;
}