我正在尝试编写一个包含公共线程对象的类,最后我想在类之外访问这个线程,但是出现了一些错误,为什么?
该类定义为:
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;
};我正在尝试访问线程成员:
scoped_thread th(std::thread(f));
th.t.join();最后,错误是:
error: request for member 't' in 'th', which is of non-class type 'scoped_thread(std::thread)'发布于 2021-03-30 11:06:09
scoped_thread th(std::thread(f));是名为th的函数的声明,返回scoped_thread并将std::thread作为参数。它不是scoped_thread类型的对象的声明。当然,该函数没有名为t或其他名称的成员。
另请参阅:most vexing parse。
发布于 2021-03-30 11:10:09
你遇到了most vexing parse。C++认为您声明的是一个名为th的函数,而不是一个对象。在C++的最新版本中,要更正此问题,可以使用大括号而不是圆括号。
scoped_thread th{std::thread{f}}; // compiles as expectedhttps://stackoverflow.com/questions/66864184
复制相似问题