std::thread Why object is copied twice?

前端 未结 3 2094
时光说笑
时光说笑 2020-12-03 16:16

Why in the example code below, object is copied twice? According documentation constructor of thread class copies all arguments to thread-local storage so we have reason for

3条回答
  •  情深已故
    2020-12-03 16:29

    The object is copied twice because the object cannot be moved. The standard does not require this, but it is legitimate behavior.

    What's happening inside of the implementation is that it seems to be doing a decay_copy of the parameters, as required by the standard. But it doesn't do the decay_copy into the final destination; it does it into some internal, possibly stack, storage. Then it moves the objects from that temporary storage to the final location within the thread. Since your type is not moveable, it must perform a copy.

    If you make your type moveable, you'll find that the second copy becomes a move.

    Why might an implementation do this, rather than just copying directly into the final destination? There could be any number of implementation-dependent reasons. It may have just been simpler to build a tuple of the function+parameters on the stack, then move that into the eventual destination.

提交回复
热议问题