From 658f09f7f153b1e4d9d2167f567cebd0245057dc Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Sun, 17 Feb 2019 14:52:45 +0000 Subject: Allow moving of ResourceHandles --- libadhocutil/resourcePool.h | 4 ++++ libadhocutil/resourcePool.impl.h | 18 ++++++++++++++++ libadhocutil/unittests/testResourcePool.cpp | 32 +++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) diff --git a/libadhocutil/resourcePool.h b/libadhocutil/resourcePool.h index 9bb03f6..bcc870b 100644 --- a/libadhocutil/resourcePool.h +++ b/libadhocutil/resourcePool.h @@ -26,10 +26,14 @@ namespace AdHoc { ResourceHandle(const std::shared_ptr &); /// Create a reference to an existing resource. ResourceHandle(const ResourceHandle &); + /// Move reference to an existing resource. + ResourceHandle(ResourceHandle &&); ~ResourceHandle(); /// Reference to an existing resource. void operator=(const ResourceHandle &); + /// Move reference to an existing resource. + void operator=(ResourceHandle &&); /// Access to the resource. Resource * operator->() const; /// Access to the resource. diff --git a/libadhocutil/resourcePool.impl.h b/libadhocutil/resourcePool.impl.h index 49f91a5..1f605a5 100644 --- a/libadhocutil/resourcePool.impl.h +++ b/libadhocutil/resourcePool.impl.h @@ -24,6 +24,13 @@ namespace AdHoc { { } + template + ResourceHandle::ResourceHandle(ResourceHandle && rh) : + resource(rh.resource) + { + rh.decRef(); + } + template ResourceHandle::~ResourceHandle() { @@ -80,6 +87,17 @@ namespace AdHoc { resource = rh.resource; } + template + void + ResourceHandle::operator=(ResourceHandle && rh) + { + if (resource) { + decRef(); + } + resource = rh.resource; + rh.decRef(); + } + template void ResourceHandle::decRef() diff --git a/libadhocutil/unittests/testResourcePool.cpp b/libadhocutil/unittests/testResourcePool.cpp index e37cc85..04e66b8 100644 --- a/libadhocutil/unittests/testResourcePool.cpp +++ b/libadhocutil/unittests/testResourcePool.cpp @@ -146,6 +146,38 @@ BOOST_AUTO_TEST_CASE( getMineNoCurrent ) BOOST_REQUIRE_THROW(pool.getMine(), AdHoc::NoCurrentResource); } +BOOST_AUTO_TEST_CASE( move ) +{ + TRP pool; + { + auto r1 = pool.get(); + BOOST_CHECK_EQUAL(pool.inUseCount(), 1); + BOOST_CHECK(r1); + { + auto r2(std::move(r1)); + BOOST_CHECK_EQUAL(pool.inUseCount(), 1); + BOOST_CHECK(!r1); + BOOST_CHECK(r2); + + r1 = std::move(r2); + BOOST_CHECK_EQUAL(pool.inUseCount(), 1); + BOOST_CHECK(r1); + BOOST_CHECK(!r2); + + r2 = pool.get(); + BOOST_CHECK_EQUAL(pool.inUseCount(), 2); + BOOST_CHECK(r2); + + r1 = std::move(r2); + BOOST_CHECK_EQUAL(pool.inUseCount(), 1); + BOOST_CHECK(r1); + BOOST_CHECK(!r2); + } + BOOST_CHECK_EQUAL(pool.inUseCount(), 1); + } + BOOST_CHECK_EQUAL(pool.inUseCount(), 0); +} + BOOST_AUTO_TEST_CASE( discard ) { TRP pool; -- cgit v1.2.3