New idiom for creating non-movable objects with the builder pattern #2025
elBoberido
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Currently, when an object is not movable, the builder
createmethod takes an out parameter reference to anoptional<T>and returns anexpected<void, Error>. This approach has a few drawbacks:Tinoption<T>also cannot be initialized when declaredreseton theoptionany time and therefore theoretically one have to take care of this null-abilityI would much more prefer the following idiom shown with the
Mutexas exampleMutexStorage m_mutexStorage; Mutex m_mutex{MutexBuilder().create(m_mutexStorage).expect("Valid Mutex")};with
and
RefTrackerSourcewould provide the memory for an atomic refcount andRefTrackerwould access this memory via a relocatable pointer. WhenRefTrackerSourceis destroyed but the refcount is not zero, the application will be terminated. This has the advantage that one cannot accidentally reset theMutex(or theSemaphorewhich also uses this idiom). The only disadvantage is thatMutexcould easily be moved to another thread but this could be prevented by adding anassert(false, "should not be moved")to the move ctor ofMutex. The move ctor will not be called on creation due to RVO but the move ctor must still be declared. This limitation is lifted with C++17 and then the runtime error would be propagated to a compile time error when one would try to move theMutex. In this case, theRefTrackerwould not be required, only theMutexStorageandMutexclasses.Beta Was this translation helpful? Give feedback.
All reactions