https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69724

            Bug ID: 69724
           Summary: Unnecessary temporary object during std::thread
                    construction
           Product: gcc
           Version: 6.0
            Status: UNCONFIRMED
          Severity: enhancement
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: redi at gcc dot gnu.org
  Target Milestone: ---

#include <thread>
#include <cstdio>

class F {
public:
    F() { std::puts("create"); }
    ~F() { std::puts("destroy"); }
    F(const F&) { std::puts("copy"); }
    F(F&&) noexcept { std::puts("move"); }
    void run() { }
};

int main()
{
  std::thread{&F::run, F{}}.join();
}

prints:

create
move
move
destroy
destroy
destroy

The standard requires a copy to be made, so one of the move constructions is
required, but a more efficient result would be:

create
move
destroy
destroy

This could be done by removing the call to __bind_simple() and constructing the
_Bind_simple member of the thread::_State_impl directly, rather than returning
by value from __bind_simple() and then moving that value into the member.

However, the benefit for most types is probably small so the additional
complexity might not be worth it.

Reply via email to