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>
17 #include <AD/gc/markswp.h>
21 MarkSweepGC marksweep
;
25 int total_created
= 0;
26 int total_destroyed
= 0;
27 int current_trial
= 0;
30 class TEST
: public GCObject
{
35 TEST(int t
, int tr
) : tag(t
), trial(tr
)
36 { for (int i
= 0; i
< 30; i
++) junk
[i
] = i
+ tag
;
37 total_created
++; created
++; }
38 ~TEST() { total_destroyed
++; if (trial
== current_trial
) destroyed
++; }
41 { assert(HM::page_gc(this) == GC::get_default_gc().gc_id());
43 for (int i
= 0; i
< 30; i
++) assert(junk
[i
] == i
+ tag
);
48 WeakPointer
<TEST
> wps
[TRIALS
];
50 void do_tests(int trial
)
54 cout
<< "Trial number " << trial
<< "\n" << flush
;
56 current_trial
= trial
;
62 // Allocate a bunch of stuff
64 for (i
= 0; i
< TRIALS
; i
++)
65 wps
[i
] = ps
[i
] = new TEST(i
,trial
);
67 cout
<< "Data has been allocated\n" << flush
;
69 GC::garbage_collect();
72 // Make sure all the weakpointers are alive even after garbage collection.
74 for (i
= 0; i
< TRIALS
; i
++) {
75 assert (! wps
[i
].is_null());
80 // Delete the non-weak version.
82 for (i
= 0; i
< TRIALS
; i
++) {
87 // Check the ones that are still alive
89 for (alive
= 0, i
= 0; i
< TRIALS
; i
++) {
90 if (! wps
[i
].is_null()) {
97 GC::garbage_collect();
100 // Check the ones that are still alive, again.
102 for (alive
= 0, i
= 0; i
< TRIALS
; i
++) {
103 if (! wps
[i
].is_null()) {
109 cout
<< " Created = " << created
110 << " Destroyed = " << destroyed
111 << " Alive = " << alive
<< '\n' << flush
;
113 assert (created
== alive
+ destroyed
);
115 // Make sure at least 80% of all objects are collected.
116 assert (TRIALS
* 8 / 10 <= destroyed
);
121 GC::set_default_gc(marksweep
);
122 GC::get_default_gc().set_finalization(true);
123 cout
<< "Testing the weak pointers facility\n" << flush
;
125 for (int i
= 1; i
<= trials
; i
++)
128 cout
<< " Total created = " << total_created
129 << " Total destroyed = " << total_destroyed
<< '\n';
131 GC::get_default_gc().print_statistics(cout
);
132 cout
<< "The weakpointers facility seems to be ok\n" << flush
;