1// This file's extension implies that it's C, but it's really -*- C++ -*-.
3 * Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration.
7 * @file CxxUtils/CachedUniquePtr.icc
8 * @author scott snyder <snyder@bnl.gov>
10 * @brief Cached unique_ptr with atomic update.
18 * @brief Default constructor. Sets the element to null.
22CachedUniquePtrT<T>::CachedUniquePtrT()
25 //cppcheck-suppress missingReturn; false positive
30 * @brief Constructor from an element.
34CachedUniquePtrT<T>::CachedUniquePtrT (std::unique_ptr<T> elt)
35 : m_ptr (elt.release())
41 * @brief Move constructor.
45CachedUniquePtrT<T>::CachedUniquePtrT (CachedUniquePtrT&& other) noexcept
46 : m_ptr (other.release().release())
57CachedUniquePtrT<T>::operator= (CachedUniquePtrT&& other) noexcept
60 store (other.release());
71CachedUniquePtrT<T>::~CachedUniquePtrT()
78 * @brief Atomically set the element. If already set, then @c elt is discarded.
79 * @param elt The new value for the element.
81 * If the current value of the element is null, then set it to @c elt.
82 * Otherwise, delete @c elt.
83 * This is done atomically.
84 * Returns the final value of the element.
88T* CachedUniquePtrT<T>::set (std::unique_ptr<T> elt) const
90 // Set the element to ELT if it is currently null.
91 T* ptr = elt.release();
92 T* expected = nullptr;
93 if (!m_ptr.compare_exchange_strong (expected, ptr)) {
94 // Was already set. Delete the new value.
103 * @brief Store a new value to the element.
104 * Not compatible with other concurrent access.
108void CachedUniquePtrT<T>::store (std::unique_ptr<T> elt) noexcept
110 T* old = m_ptr.exchange (elt.release());
116 * @brief Return the current value of the element.
121CachedUniquePtrT<T>::get() const
128 * @brief Dereference the element.
133CachedUniquePtrT<T>::operator*() const
140 * @brief Dereference the element.
145CachedUniquePtrT<T>::operator->() const
152 * @brief Test if the element is null.
156CachedUniquePtrT<T>::operator bool() const
158 return get() != nullptr;
163 * @brief Transfer ownership from the element: return the current value as a
164 * unique_ptr, leaving the element null.
169CachedUniquePtrT<T>::release() noexcept
171 T* old = m_ptr.exchange (nullptr);
172 return std::unique_ptr<T> (old);
176} // namespace CxxUtils