Std :: thread Why is an object copied twice?

Why is the code copied twice in the example below? According to the documentation constructor, the stream class copies all arguments to the local stream store, so we have a reason for the first copy. How about a second?

class A {
public:
    A() {cout << "[C]" << endl;}
    ~A() {cout << "[~D]" << endl;}
    A(A const& src) {cout << "[COPY]" << endl;}
    A& operator=(A const& src) {cout << "[=}" << endl; return *this;}

    void operator() () {cout << "#" << endl;}
};

void foo()
{
    A a;
    thread t{a};
    t.join();
}

Output above:

[C]
[COPY]
[COPY]
[~D]
#
[~D]
[~D]

Edit: Well yes, adding a move constructor:

A(A && src) {cout << "[MOVE]" << endl;}

The output is as follows:

[C]
[COPY]
[MOVE]
[~D]
#
[~D]
[~D]
+5
source share
3 answers

For everything you want to move or avoid copies, prefer to move the constructors and std::move.

But why doesn't this happen automatically for me?

++ . , std::move(). , , , . .

, a , std::move(a) ( std::thread). , , , std:: thread , , std:: thread ( ). , ( / , , : , ).

, std::move . V++ ( CTP ), , MSVC ( ) Copy.

+4

: thread t {std:: move (a)};

0

, . , .

, , decay_copy , . decay_copy ; , , . . , .

, , .

, ? , . , tuple + , .

0

All Articles