Sequential Quantum Gate Decomposer  v1.9.6
Powerful decomposition of general unitarias into one- and two-qubit gates gates
utils.hpp
Go to the documentation of this file.
1 #include <atomic>
2 #include <memory>
3 #include <utility>
4 
5 template<typename T>
7 public:
8  SmartAtomicPtr() = default;
9 
10  explicit SmartAtomicPtr(std::shared_ptr<T> p) {
11  std::atomic_store(&ptr_, std::move(p));
12  }
13 
14  // Copy / assign load the current shared_ptr atomically
16  std::atomic_store(&ptr_, std::atomic_load(&other.ptr_));
17  }
19  if (this != &other) {
20  std::atomic_store(&ptr_, std::atomic_load(&other.ptr_));
21  }
22  return *this;
23  }
24 
25  // Move ops
26  SmartAtomicPtr(SmartAtomicPtr&& other) noexcept {
27  auto p = std::atomic_load(&other.ptr_);
28  std::atomic_store(&ptr_, std::move(p));
29  std::atomic_store(&other.ptr_, std::shared_ptr<T>{});
30  }
32  if (this != &other) {
33  std::atomic_store(&ptr_, std::atomic_load(&other.ptr_));
34  std::atomic_store(&other.ptr_, std::shared_ptr<T>{});
35  }
36  return *this;
37  }
38 
39  ~SmartAtomicPtr() = default; // shared_ptr cleans up when last ref dies
40 
41  // Replace the pointer; old value is released when 'old' goes out of scope
42  void update(std::shared_ptr<T> p) {
43  auto old = std::atomic_exchange(&ptr_, std::move(p));
44  (void)old; // dropping 'old' decrements refcount
45  }
46 
47  // Convenience for raw pointer input (creates sole owner control block)
48  void update(T* p) { update(std::shared_ptr<T>(p)); }
49 
50  // Readers get a shared_ptr snapshot, safe against concurrent updates
51  std::shared_ptr<T> get() const {
52  return std::atomic_load(&ptr_);
53  }
54 
55 private:
56  std::shared_ptr<T> ptr_;
57 };
SmartAtomicPtr(const SmartAtomicPtr &other)
Definition: utils.hpp:15
SmartAtomicPtr()=default
void update(T *p)
Definition: utils.hpp:48
void update(std::shared_ptr< T > p)
Definition: utils.hpp:42
SmartAtomicPtr(SmartAtomicPtr &&other) noexcept
Definition: utils.hpp:26
SmartAtomicPtr & operator=(const SmartAtomicPtr &other)
Definition: utils.hpp:18
SmartAtomicPtr & operator=(SmartAtomicPtr &&other) noexcept
Definition: utils.hpp:31
SmartAtomicPtr(std::shared_ptr< T > p)
Definition: utils.hpp:10
std::shared_ptr< T > ptr_
Definition: utils.hpp:56
Definition: T.h:11
~SmartAtomicPtr()=default