mercredi 7 juillet 2021

Anonymous callable object is not executed by a std::thread [duplicate]

I've been practicing some C/C++ threading tutorial. And I found the following sample code didn't not work as I expected.

class CallableObject
{
public:
    CallableObject(): _i(1000) {}
    
    CallableObject(int i): _i(i) {
        std::cout << "constructor called\n";
    }
    
    void operator()() 
    {

        std::cout <<  _i << endl;  
    }
private:
    int _i;
};



int main()
{
    CallableObject callable_object(100);
    std::thread t(CallableObject());
    
    std::thread t2(CallableObject(10));
    
    std::thread t3(callable_object);
    
    sleep(10);
    return 0;
}

I expected that even given a anonymous callable object, the thread t still would execute the operator() and print out 1000. But the compiled result is this:

constructor called
constructor called
100
10
terminate called without an active exception


...Program finished with exit code 0

Could anyone explain why the thread t is not constructed successfully? Is this issue related to object lifetime or r-value references?

Aucun commentaire:

Enregistrer un commentaire