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
-
Currently, when an object is not movable, the builder
create
method takes an out parameter reference to anoptional<T>
and returns anexpected<void, Error>
. This approach has a few drawbacks:T
inoption<T>
also cannot be initialized when declaredreset
on theoption
any time and therefore theoretically one have to take care of this null-abilityI would much more prefer the following idiom shown with the
Mutex
as examplewith
and
RefTrackerSource
would provide the memory for an atomic refcount andRefTracker
would access this memory via a relocatable pointer. WhenRefTrackerSource
is destroyed but the refcount is not zero, the application will be terminated. This has the advantage that one cannot accidentally reset theMutex
(or theSemaphore
which also uses this idiom). The only disadvantage is thatMutex
could 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, theRefTracker
would not be required, only theMutexStorage
andMutex
classes.Beta Was this translation helpful? Give feedback.
All reactions