c++embeddedmove-semanticsstd-expected

How to avoid calling the destructor twice when using a factory function with a std::expected return without runtime costs


It's about embedded C++. Let's assume I have a struct Timer_t.

To create a new object

We can't use exceptions on the device and to intiailize the Timer we can get errors.

That's why

Since we use C++ and people tend to fail (calling me out here too often)

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.

Is there a better cleaner idea to solve that problem? I can't be the only one with it.


Solution

  • Thanks to RVO (return value optimization), the problem you're describing doesn't really exist in C++. Consider the following code:

    #include <expected>
    
    struct Timer_t {
        Timer_t();
        Timer_t(Timer_t&&);
        Timer_t& operator=(Timer_t&&);
        ~Timer_t();
    };
    
    struct Error_t {
        Error_t();
        Error_t(Error_t&&);
        Error_t& operator=(Error_t&&);
        ~Error_t();
    }; 
    
    std::expected<Timer_t, Error_t> makeTimer() {
        return {};
    }
    
    int main() {
        auto timer = makeTimer();
    }
    

    Without RVO, it looks like return {} first has to create a default-constructed std::expected, which would call Timer_t(), and then auto timer = makeTimer(); would call the move constructor because the right hand side is a prvalue.

    However, that's not how it works since C++17:

    Both of these optimizations are mandatory, so it is guaranteed that we are only calling Timer_t() once, and then ~Timer_t() when timer goes out of scope. As expected, this is the compiler output:

    main:
            sub     rsp, 24
            lea     rdi, [rsp+14]
            call    Timer_t::Timer_t() [complete object constructor]
            lea     rdi, [rsp+14]
            mov     BYTE PTR [rsp+15], 1
            call    Timer_t::~Timer_t() [complete object destructor]
            xor     eax, eax
            add     rsp, 24
            ret
    

    See live example using GCC 13 with -std=c++2b -O2.