Skip to content

Commit 2614c5b

Browse files
committed
Add reset() method to small_shared_two_way_ptrt
This adds a reset() method which clears the contents of the shared pointer. Furthermore, the code to remove a reference to the pointed-to object is factored out into a method destruct(). The method is used both by the destructor and by reset().
1 parent d61900d commit 2614c5b

File tree

2 files changed

+39
-23
lines changed

2 files changed

+39
-23
lines changed

src/util/small_shared_two_way_ptr.h

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -101,30 +101,13 @@ class small_shared_two_way_ptrt final
101101

102102
~small_shared_two_way_ptrt()
103103
{
104-
if(!p)
105-
{
106-
return;
107-
}
108-
109-
auto use_count = p->use_count();
104+
destruct();
105+
}
110106

111-
if(use_count == 1)
112-
{
113-
if(p->is_derived_u())
114-
{
115-
U *u = static_cast<U *>(p);
116-
delete u;
117-
}
118-
else
119-
{
120-
V *v = static_cast<V *>(p);
121-
delete v;
122-
}
123-
}
124-
else
125-
{
126-
p->decrement_use_count();
127-
}
107+
void reset()
108+
{
109+
destruct();
110+
p = nullptr;
128111
}
129112

130113
void swap(small_shared_two_way_ptrt &rhs)
@@ -186,6 +169,34 @@ class small_shared_two_way_ptrt final
186169
}
187170

188171
private:
172+
void destruct()
173+
{
174+
if(!p)
175+
{
176+
return;
177+
}
178+
179+
auto use_count = p->use_count();
180+
181+
if(use_count == 1)
182+
{
183+
if(p->is_derived_u())
184+
{
185+
U *u = static_cast<U *>(p);
186+
delete u;
187+
}
188+
else
189+
{
190+
V *v = static_cast<V *>(p);
191+
delete v;
192+
}
193+
}
194+
else
195+
{
196+
p->decrement_use_count();
197+
}
198+
}
199+
189200
pointeet *p = nullptr;
190201
};
191202

unit/util/small_shared_two_way_ptr.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ TEST_CASE("Small shared two-way pointer")
6161
SECTION("Basic")
6262
{
6363
spt sp1;
64+
REQUIRE(!sp1);
6465
REQUIRE(sp1.use_count() == 0);
6566

6667
const d1t *p;
@@ -86,6 +87,10 @@ TEST_CASE("Small shared two-way pointer")
8687
REQUIRE(sp1.use_count() == 3);
8788
REQUIRE(sp2.use_count() == 3);
8889
REQUIRE(sp3.use_count() == 3);
90+
91+
sp1.reset();
92+
REQUIRE(!sp1);
93+
REQUIRE(sp1.use_count() == 0);
8994
}
9095

9196
SECTION("Creation")

0 commit comments

Comments
 (0)