From: Matthias Maier Date: Fri, 27 Oct 2023 04:29:55 +0000 (-0500) Subject: base: add Lazy::has_value() method X-Git-Tag: relicensing~355^2~1 X-Git-Url: https://gitweb.dealii.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=8accc6ad2c1f8a30be876feccc1af642f5eb011f;p=dealii.git base: add Lazy::has_value() method --- 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