diff options
author | Jacques Lucke <jacques@blender.org> | 2022-03-02 14:51:21 +0300 |
---|---|---|
committer | Jacques Lucke <jacques@blender.org> | 2022-03-02 14:51:21 +0300 |
commit | c23ec04b4e30f300a670f1cb1dc882e0608d09ad (patch) | |
tree | fbc914a9ccc72a03c894ec91b5c3a16e3537d04c /source/blender/blenlib/tests | |
parent | 721335553ccb5ce4f7a374b958b7d65befa319df (diff) |
BLI: add scoped-defer utility to add RAII-like behavior to C types
This utility is useful when using C types that own some resource in
a C++ file. It mainly helps in functions that have multiple return
statements, but also simplifies code by moving construction and
destruction closer together.
Differential Revision: https://developer.blender.org/D14215
Diffstat (limited to 'source/blender/blenlib/tests')
-rw-r--r-- | source/blender/blenlib/tests/BLI_memory_utils_test.cc | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/source/blender/blenlib/tests/BLI_memory_utils_test.cc b/source/blender/blenlib/tests/BLI_memory_utils_test.cc index 993434ddeba..ab716e5d011 100644 --- a/source/blender/blenlib/tests/BLI_memory_utils_test.cc +++ b/source/blender/blenlib/tests/BLI_memory_utils_test.cc @@ -176,4 +176,29 @@ static_assert(!is_same_any_v<int, float, bool>); static_assert(!is_same_any_v<int, float>); static_assert(!is_same_any_v<int>); +TEST(memory_utils, ScopedDefer1) +{ + int a = 0; + { + BLI_SCOPED_DEFER([&]() { a -= 5; }); + { + BLI_SCOPED_DEFER([&]() { a *= 10; }); + a = 5; + } + } + EXPECT_EQ(a, 45); +} + +TEST(memory_utils, ScopedDefer2) +{ + std::string s; + { + BLI_SCOPED_DEFER([&]() { s += "A"; }); + BLI_SCOPED_DEFER([&]() { s += "B"; }); + BLI_SCOPED_DEFER([&]() { s += "C"; }); + BLI_SCOPED_DEFER([&]() { s += "D"; }); + } + EXPECT_EQ(s, "DCBA"); +} + } // namespace blender::tests |