offa пре 7 година
родитељ
комит
334c7f3b9e
2 измењених фајлова са 42 додато и 2 уклоњено
  1. +17
    -2
      include/unique_resource.h
  2. +25
    -0
      test/UniqueResourceTest.cpp

+ 17
- 2
include/unique_resource.h Прегледај датотеку

@@ -29,7 +29,10 @@ namespace sr
{
public:

explicit unique_resource_t(Ressource&& res, Deleter&& deleter, bool shouldrun = true) noexcept : m_deleter(std::move(deleter))
explicit unique_resource_t(Ressource&& res, Deleter&& deleter, bool shouldrun = true) noexcept : m_resource(std::move(res)),
m_deleter(std::move(deleter)),
m_execute_on_destruction(true)

{
static_cast<void>(res);
static_cast<void>(shouldrun);
@@ -38,13 +41,25 @@ namespace sr

~unique_resource_t()
{
m_deleter();
if( m_execute_on_destruction == true )
{
m_deleter();
}
}


const Ressource& release() noexcept
{
m_execute_on_destruction = false;
return m_resource;
}


private:

Ressource m_resource;
Deleter m_deleter;
bool m_execute_on_destruction;
};



+ 25
- 0
test/UniqueResourceTest.cpp Прегледај датотеку

@@ -36,3 +36,28 @@ TEST_CASE("deleter called on destruction", "[UniqueResource]")
REQUIRE(calls == 1);
}

TEST_CASE("deleter is not called if released", "[UniqueResource]")
{
std::size_t calls{0};
constexpr Handle handle{3};

{
auto guard = sr::unique_resource(handle, [&calls] { ++calls; });
guard.release();
}

REQUIRE(calls == 0);
}


TEST_CASE("release returns reference to resource", "[UniqueResource]")
{
constexpr Handle handle{3};

auto guard = sr::unique_resource(handle, [] { });
const auto result = guard.release();

REQUIRE(handle == result);
}



Loading…
Откажи
Сачувај