5

オブジェクトを別のオブジェクトに移動できない理由は何std::threadですか? 役に立つ場面もある。例えば:

着信ソケット接続を受け入れるループを作成します。着信接続を、接続を処理する別のスレッドに移動するとよいでしょう。受け入れループで接続はもう必要ありません。では、なぜポインターを作成する必要があるのでしょうか。

小さなテストケース:

#include <iostream>
#include <thread>

using namespace std;

class Pointertest
{
public:
    Pointertest() {cout << "Constructor";}
    Pointertest(Pointertest &pointertest) {cout << "Copy";}
    Pointertest(Pointertest &&pointertest) {cout << "Move";}
    ~Pointertest() {cout << "Destruct";}
};

void foo(Pointertest &&pointertest)
{

}

int main()
{
    Pointertest pointertest;

    foo(std::move(pointertest)); //Works
    thread test(foo,std::move(pointertest)); //**cannot convert parameter 1 from 'Pointertest' to 'Pointertest &&'**
}
4

2 に答える 2

5

可能です。コピー コンストラクターのシグネチャを修正すると、うまくいきます。

class Pointertest
{
public:
    Pointertest() {cout << "Constructor";}
    Pointertest(Pointertest const& pointertest) {cout << "Copy";}
//                          ^^^^^^
    Pointertest(Pointertest &&pointertest) {cout << "Move";}
    ~Pointertest() {cout << "Destruct";}
};

threadまた、オブジェクトがスコープ外になる前に、スレッドに参加する (またはスレッドから切り離す) ことを忘れないでください。

int main()
{
    Pointertest pointertest;
    thread test(foo, std::move(pointertest));

    test.join();
//  ^^^^^^^^^^^^
}
于 2013-05-13T17:49:06.403 に答える