Reputation: 31
I'm trying to write a class include a public thread object, and finally I want to access this thread ouside the class, but there are some errors, why?
The class defined as:
class scoped_thread {
public:
std::thread t;
explicit scoped_thread(std::thread t_) : t(std::move(t_)) {
if (!t.joinable())
throw std::logic_error("No thread");
}
~scoped_thread() {
// t.join();
}
scoped_thread(scoped_thread const &) = delete;
scoped_thread & operator = (scoped_thread const &) = delete;
};
and I'm try to access thread member:
scoped_thread th(std::thread(f));
th.t.join();
At last, the error is:
error: request for member 't' in 'th', which is of non-class type 'scoped_thread(std::thread)'
Upvotes: 1
Views: 53
Reputation: 1309
You've run into the most vexing parse. C++ thinks you've declared a function named th
instead of an object. In recent versions of C++, to correct the issue you can use curly braces instead of parentheses.
scoped_thread th{std::thread{f}}; // compiles as expected
Upvotes: 3
Reputation: 52621
scoped_thread th(std::thread(f));
is a declaration of a function named th
, returning scoped_thread
and taking std::thread
as a parameter. It's not a declaration of an object of type scoped_thread
. Naturally, the function doesn't have members, named t
or otherwise.
See also: most vexing parse.
Upvotes: 3