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

huangapple go评论84阅读模式
英文:

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:

  • the constructor is private
  • we have a factory function as a public member makeTimer()

We can't use exceptions on the device and to initialize 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 behavior. Therefore it's per standard correct, but annoying.

In the context of embedded, I see there's 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 the use of 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.

英文:

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&lt;Timer_t,Error_t&gt;

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() -&gt; Timer_t() -&gt; std::move/Timer_t(Timer_t &amp;&amp;) -&gt; ~Timer_t() -&gt;  program ends -&gt; ~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 &amp; 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.

答案1

得分: 7

感谢RVO(返回值优化),你描述的问题在C++中实际上并不存在。考虑以下代码:

#include &lt;expected&gt;

struct Timer_t {
    Timer_t();
    Timer_t(Timer_t&amp;&amp;);
    Timer_t&amp; operator=(Timer_t&amp;&amp;);
    ~Timer_t();
};

struct Error_t {
    Error_t();
    Error_t(Error_t&amp;&amp;);
    Error_t&amp; operator=(Error_t&amp;&amp;);
    ~Error_t();
}; 

std::expected&lt;Timer_t, Error_t&gt; makeTimer() {
    return {};
}

int main() {
    auto timer = makeTimer();
}

没有RVO,似乎return {}首先必须创建一个默认构造的std::expected,这会调用Timer_t(),然后auto timer = makeTimer();会调用移动构造函数,因为右侧是一个prvalue。

然而,自C++17以来它不是这样工作的

  • auto timer = makeTimer() 受到复制省略的影响,因此不会调用移动构造函数。
  • return {};中,因为{} 是一个与返回类型相同的prvalue,它受到RVO的影响。

这两个优化都是强制性的,因此我们可以确保只调用了Timer_t()一次,然后在timer超出作用域时调用~Timer_t()。正如预期的那样,这是编译器的输出:

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

请查看使用GCC 13和-std=c++2b -O2在线示例

英文:

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

#include &lt;expected&gt;

struct Timer_t {
    Timer_t();
    Timer_t(Timer_t&amp;&amp;);
    Timer_t&amp; operator=(Timer_t&amp;&amp;);
    ~Timer_t();
};

struct Error_t {
    Error_t();
    Error_t(Error_t&amp;&amp;);
    Error_t&amp; operator=(Error_t&amp;&amp;);
    ~Error_t();
}; 

std::expected&lt;Timer_t, Error_t&gt; 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:

  • auto timer = makeTimer() is subject to copy elision, so no move constructor is being called.
  • in return {};, because the {} is a prvalue with the same type as the return type, it is subject to RVO.

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.

huangapple
  • 本文由 发表于 2023年6月12日 20:35:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定