DLG4::VolumeBuilders
A fluent interface for Geant4 geometry definition.
Loading...
Searching...
No Matches
disableable_shared_from_this.hh
Go to the documentation of this file.
1#pragma once
2#include <atomic>
3#include <iostream>
4#include <memory>
14//
15
16#ifndef DELAYEDENABLESHAREDFROMTHIS_HH
17#define DELAYEDENABLESHAREDFROMTHIS_HH
18
19namespace DLG4::Utilities {
20 /***
21 *@class DLG4::Utilities::disableable_shared_from_this
22 *@brief A dis-armable shared_from_this()
23* This solves the problem of not being able to call shared_from_this() before a shared pointer is
24* attached to the argument. Factories are not ALWAYS a practical solution.
25* This allows a ctor to disable shared with this to call fluent methods non-fluently (they return nullptr) without crashing
26* The enable_shared_with_this can then be re-armed before the last return call.
27*
28* Just inherit from it as normal and call set_shared_from_this_enabled(false) to disable
29* and set_shared_from_this_enabled(true) to re-enable before exit.
30*
31* Warning... you still have the limitation that you cannot CHAIN calls before the the pointer is set.
32*/
33 template <typename T>
34 class disableable_shared_from_this: public std::enable_shared_from_this<T> {
35 protected:
36 // Default to true for normal shared_from_this() behavior
37 std::atomic<bool> is_enabled_{true};
38
40 virtual ~disableable_shared_from_this() = default;
41
42 public:
43 // ReSharper disable once CppHidingFunction
44 std::shared_ptr<T> shared_from_this() {
45 if (is_enabled_) {
46 return std::enable_shared_from_this<T>::shared_from_this();
47 } else {
48 return nullptr;
49 }
50 }
51
52 std::shared_ptr<const T> shared_from_this() const {
53 if (is_enabled_) {
54 return std::enable_shared_from_this<T>::shared_from_this();
55 } else {
56 return nullptr;
57 }
58 }
59
60 void set_shared_from_this_enabled(bool enabled) {
61 is_enabled_ = enabled;
62 }
63 };
64}
65
66#endif //ARMSHAREDFROMTHIS_HH