"Empty" std::thread is not moved properly?

Here by "empty std::thread" means a std::thread object with "no thread of execution"
According to cpp reference, that alose means "a new thread object which does not represent a thread."

In this example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class threadRAII {
private:
    std::thread th;
public:
    //only move ctor is allowed
    explicit threadRAII(std::thread&& t ) : th(std::move(t)) {}
   // ...
};

int main()
{
    std::thread th(); 
    threadRAII tr(std::move(th));
}


I got this error:
main.cpp:30:32: error: no matching function for call to ‘threadRAII::threadRAII(std::thread (&)())’
threadRAII tr(std::move(th));


Not sure why? (does this have to do with std::thread th() being interpreted as some function, as per "most vexing parse" by Scott Meyers?)
Last edited on
https://en.cppreference.com/w/cpp/thread/thread/thread

In the example, it shows:

std::thread t1; // t1 is not a thread

Maybe that is your problem?

Edit:

I mean on line 3, that is not a thread.

What is the point of your code? Why are you trying to move an empty thread ?(even if it had a function associated with it)
Last edited on
does this have to do with std::thread th() being interpreted as some function

Yeah, it's in the error message:
no matching function for call to ‘threadRAII::threadRAII(std::thread (&)())

It says you can't call thread's constructor with an argument of type std::thread (&)().
That is an lvalue reference to function returning std::thread and accepting no arguments.

That hints at the problem on line 12
std::thread th();
Which declares a function named th.

But a class named ThreadRAII seems redundant, did you want std::jthread?
https://en.cppreference.com/w/cpp/thread/jthread
Hi guys,

What is the point of your code? Why are you trying to move an empty thread ?(even if it had a function associated with it)
This is part of an exception-safe class that I implemented. I wanted to have a move constructor only.

But a class named ThreadRAII seems redundant, did you want std::jthread?

jthread sounds like a good idea, but it's new in C++20. I'm using C++ 14, so I have to implement that exception-safe thread myself. Thanks for the heads-up though!

Which declares a function named th.

That's completely the cause of the error, i.e, "the most vexing parse" by Scott Meyers
Topic archived. No new replies allowed.