From 8accc6ad2c1f8a30be876feccc1af642f5eb011f Mon Sep 17 00:00:00 2001 From: Matthias Maier Date: Thu, 26 Oct 2023 23:29:55 -0500 Subject: [PATCH] base: add Lazy::has_value() method --- include/deal.II/base/lazy.h | 26 ++++++++++++++++++++++++-- tests/base/lazy_01.cc | 4 ++++ tests/base/lazy_01.output | 2 ++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/include/deal.II/base/lazy.h b/include/deal.II/base/lazy.h index e2c5f22b06..307fbc9708 100644 --- a/include/deal.II/base/lazy.h +++ b/include/deal.II/base/lazy.h @@ -138,6 +138,14 @@ public: ensure_initialized(const Callable &creator) const; + /** + * Returns true if the contained object has been initialized, otherwise + * false. + */ + bool + has_value() const; + + /** * Return a const reference to the contained object. * @@ -326,12 +334,26 @@ Lazy::ensure_initialized(const Callable &creator) const } +template +inline DEAL_II_ALWAYS_INLINE bool +Lazy::has_value() const +{ + // + // In principle it would be sufficient to solely check the atomic + // object_is_initialized because the load() is performed with "acquire" + // semantics. But just in case let's check the object.has_value() boolean + // as well: + // + return object_is_initialized && object.has_value(); +} + + template inline DEAL_II_ALWAYS_INLINE const T & Lazy::value() const { Assert( - object.has_value(), + object_is_initialized && object.has_value(), dealii::ExcMessage( "value() has been called but the contained object has not been " "initialized. Did you forget to call 'ensure_initialized()' first?")); @@ -345,7 +367,7 @@ inline DEAL_II_ALWAYS_INLINE T & Lazy::value() { Assert( - object.has_value(), + object_is_initialized && object.has_value(), dealii::ExcMessage( "value() has been called but the contained object has not been " "initialized. Did you forget to call 'ensure_initialized()' first?")); diff --git a/tests/base/lazy_01.cc b/tests/base/lazy_01.cc index 879f3c339c..b33277d5a6 100644 --- a/tests/base/lazy_01.cc +++ b/tests/base/lazy_01.cc @@ -33,11 +33,15 @@ main() { Lazy lazy_integer; + deallog << "lazy_integer.has_value() = " << lazy_integer.has_value() + << std::endl; lazy_integer.ensure_initialized([&]() { deallog << "[initializing object]" << std::endl; return 42; }); + deallog << "lazy_integer.has_value() = " << lazy_integer.has_value() + << std::endl; deallog << "lazy_integer.value() = " << lazy_integer.value() << std::endl; lazy_integer.ensure_initialized([&]() { diff --git a/tests/base/lazy_01.output b/tests/base/lazy_01.output index 7d33dd9bad..728e7260e7 100644 --- a/tests/base/lazy_01.output +++ b/tests/base/lazy_01.output @@ -1,5 +1,7 @@ +DEAL::lazy_integer.has_value() = 0 DEAL::[initializing object] +DEAL::lazy_integer.has_value() = 1 DEAL::lazy_integer.value() = 42 DEAL::lazy_integer.value() = 42 DEAL::lazy_integer.value() = ... [initializing object] ... 42 -- 2.39.5