It's about embedded C++. Let's assume I have a struct Timer_t
.
To create a new object
- the constructor is private
- we have a factory-function as a public member
makeTimer()
We can't use exceptions on the device and to intiailize the Timer we can get errors.
That's why
- the default constructors are hidden for the user
- a factory function is used
- the factory function returns
std::expected<Timer_t,Error_t>
Since we use C++ and people tend to fail (calling me out here too often)
- Constructors are powerful to initialize
- Destructors are powerful to deinitialize
Constructors are only half usable here, the factory function is this for us.
For the destructor it works nice. If we ever leave the scope we deinitialize it. That's how it should be.
Now the problem starts: if we return in makeTimer()
the Object we have a move.
To be more precise we call the move constructor
!
Therefore we have 2 objects and for the object we call the destructor.
To be more precise:
makeTimer() -> Timer_t() -> std::move/Timer_t(Timer_t &&) -> ~Timer_t() -> program ends -> ~Timer_t();
For a move, this is the expected behaviour. Therefore it's per standard correct, but annoying.
In context of embedded I see there a big risk that people will fail here when extending the code.
I only want to call the destructor once at the end.
- if I use Timer_t as a return it works! (that's what is frustrating)
- I forbid to use non-trivial types (ugh! or i never saw a good example for this specific Timer thing)
- use
Error_t makeTimer(Timer_t & uninitialized Type)
(Would kill the idea behind std::expected and makes code less "nice") - use a flag/counter like
std::shared_ptr
(extra costs...) or a simple bool.
Is there a better cleaner idea to solve that problem? I can't be the only one with it.