1 //////////////////////////////////////////////////////////////////////////////
2 // Testing the weak pointers facilities
3 // We'll allocate a bunch of dummy objects and store weakpointer referencing
4 // them into an array. The dummy objects are then throw away.
5 // We'll test three things:
6 // (1) Weakpointers do not prevent objects from being collected.
7 // (2) The objects that are still alive is reachable from the
9 // (3) The counts add up.
10 //////////////////////////////////////////////////////////////////////////////
14 #include <AD/gc/gcobject.h>
15 #include <AD/gc/weakptr.h>
16 #include <AD/gc/gcheaps.h>
22 int total_created
= 0;
23 int total_destroyed
= 0;
24 int current_trial
= 0;
27 class TEST
: public GCObject
{
32 TEST(int t
, int tr
) : tag(t
), trial(tr
)
33 { for (int i
= 0; i
< 30; i
++) junk
[i
] = i
+ tag
;
34 total_created
++; created
++; }
35 ~TEST() { total_destroyed
++; if (trial
== current_trial
) destroyed
++; }
38 { assert(HM::page_gc(this) == GC::get_default_gc().gc_id());
40 for (int i
= 0; i
< 30; i
++) assert(junk
[i
] == i
+ tag
);
45 WeakPointer
<TEST
> wps
[TRIALS
];
47 void do_tests(int trial
)
51 cout
<< "Trial number " << trial
<< "\n" << flush
;
53 current_trial
= trial
;
59 // Allocate a bunch of stuff
61 for (i
= 0; i
< TRIALS
; i
++)
62 wps
[i
] = ps
[i
] = new TEST(i
,trial
);
64 cout
<< "Data has been allocated\n" << flush
;
66 GC::garbage_collect();
69 // Make sure all the weakpointers are alive even after garbage collection.
71 for (i
= 0; i
< TRIALS
; i
++) {
72 assert (! wps
[i
].is_null());
77 // Delete the non-weak version.
79 for (i
= 0; i
< TRIALS
; i
++) {
84 // Check the ones that are still alive
86 for (alive
= 0, i
= 0; i
< TRIALS
; i
++) {
87 if (! wps
[i
].is_null()) {
94 GC::garbage_collect();
97 // Check the ones that are still alive, again.
99 for (alive
= 0, i
= 0; i
< TRIALS
; i
++) {
100 if (! wps
[i
].is_null()) {
106 cout
<< " Created = " << created
107 << " Destroyed = " << destroyed
108 << " Alive = " << alive
<< '\n' << flush
;
110 assert (created
== alive
+ destroyed
);
112 // Make sure at least 80% of all objects are collected.
113 assert (TRIALS
* 8 / 10 <= destroyed
);
118 GC::get_default_gc().set_finalization(true);
119 cout
<< "Testing the weak pointers facility\n" << flush
;
121 for (int i
= 1; i
<= trials
; i
++)
124 cout
<< " Total created = " << total_created
125 << " Total destroyed = " << total_destroyed
<< '\n';
127 GC::get_default_gc().print_statistics(cout
);
128 cout
<< "The weakpointers facility seems to be ok\n" << flush
;