Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

c++ - Why arguments moved twice when constructing std::thread

Consider this program that essentially creates std::thread that calls the function func() with arg as argument:

#include <thread>
#include <iostream>

struct foo {
   foo() = default;
   foo(const foo&) { std::cout << "copy ctor" << std::endl; }
   foo(foo&&) noexcept { std::cout << "move ctor" << std::endl; }
};

void func(foo){}

int main() {
   foo arg;
   std::thread th(func, arg);
   th.join();
}

My output is

copy ctor
move ctor
move ctor

As far as I understand arg is copied internally in the thread object and then passed to func() as an rvalue (moved). So, I expect one copy construction and one move construction.

Why is there a second move construction?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You pass argument to func by value which should constitute the second move. Apparently std::thread stores it internally one more time before calling func, which AFAIK is absolutely legal in terms of the Standard.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...