0

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?

  • 1
    You have discovered the [Most Vexing Parse](https://stackoverflow.com/questions/14077608/what-is-the-purpose-of-the-most-vexing-parse). Use `std::thread t(CallableObject{});` or `std::thread t((CallableObject()));` to indicate that `t` is **not** a function that takes a `CallableObject` and returns a `std::thread`. – Drew Dormann Jul 07 '21 at 15:35
  • 3
    Also, `sleep` is not a good way of synchronizing threads. Use `thread.join()`. – SergeyA Jul 07 '21 at 15:36
  • @DrewDormann Thank you, sir. It really helps a lot. – Lin Shien Jul 07 '21 at 15:49

0 Answers0