1 /// Unit tests for reference counting and smart pointer classes
2 #define BOOST_TEST_MODULE structure
3 #include <BoostTestTargetConfig.h>
5 #include "SGSharedPtr.hxx"
6 #include "SGWeakPtr.hxx"
8 static int instance_count = 0;
9 struct ReferenceCounted:
22 typedef SGSharedPtr<ReferenceCounted> RefPtr;
24 BOOST_AUTO_TEST_CASE( shared_ptr )
26 BOOST_REQUIRE_EQUAL( ReferenceCounted::count(0), 0 );
28 RefPtr ptr( new ReferenceCounted() );
29 BOOST_REQUIRE_EQUAL( instance_count, 1 );
30 BOOST_REQUIRE_EQUAL( ReferenceCounted::count(ptr.get()), 1 );
31 BOOST_REQUIRE_EQUAL( ptr.getNumRefs(), 1 );
34 BOOST_REQUIRE_EQUAL( ptr.getNumRefs(), 2 );
35 BOOST_REQUIRE_EQUAL( ptr2.getNumRefs(), 2 );
37 BOOST_REQUIRE_EQUAL( ptr, ptr2 );
38 BOOST_REQUIRE_EQUAL( ptr.get(), ptr2.get() );
41 BOOST_REQUIRE( !ptr.get() );
42 BOOST_REQUIRE_EQUAL( ptr.getNumRefs(), 0 );
43 BOOST_REQUIRE_EQUAL( ReferenceCounted::count(ptr2.get()), 1 );
44 BOOST_REQUIRE_EQUAL( ptr2.getNumRefs(), 1 );
47 BOOST_REQUIRE( !ptr2.get() );
48 BOOST_REQUIRE_EQUAL( ptr.getNumRefs(), 0 );
49 BOOST_REQUIRE_EQUAL( ptr2.getNumRefs(), 0 );
50 BOOST_REQUIRE_EQUAL( instance_count, 0) ;
54 public virtual SGVirtualWeakReferenced
58 public virtual SGVirtualWeakReferenced
66 BOOST_AUTO_TEST_CASE( virtual_weak_ptr )
68 SGSharedPtr<VirtualDerived> ptr( new VirtualDerived() );
69 SGWeakPtr<VirtualDerived> weak_ptr( ptr );
70 BOOST_REQUIRE_EQUAL( ptr.getNumRefs(), 1 );
72 SGSharedPtr<Base1> ptr1( weak_ptr.lock() );
73 BOOST_REQUIRE_EQUAL( ptr.getNumRefs(), 2 );
75 // converting constructor
76 BOOST_REQUIRE_EQUAL( SGSharedPtr<Base1>(weak_ptr), ptr1 );
78 SGSharedPtr<Base2> ptr2( weak_ptr.lock() );
79 BOOST_REQUIRE_EQUAL( ptr.getNumRefs(), 3 );
81 BOOST_REQUIRE( ptr != NULL );
82 BOOST_REQUIRE_EQUAL( ptr.get(), ptr1.get() );
83 BOOST_REQUIRE_EQUAL( ptr.get(), ptr2.get() );
85 SGWeakPtr<Base1> weak_base1( ptr );
86 SGWeakPtr<Base2> weak_base2( ptr );
87 ptr1 = dynamic_cast<VirtualDerived*>(weak_base1.lock().get());
88 ptr2 = dynamic_cast<VirtualDerived*>(weak_base2.lock().get());
90 BOOST_REQUIRE_EQUAL( ptr.get(), ptr1.get() );
91 BOOST_REQUIRE_EQUAL( ptr.get(), ptr2.get() );
92 BOOST_REQUIRE_EQUAL( ptr.getNumRefs(), 3 );