I have created a class named AnalyzerCore in c++ like below:
AnalyzerCore.h
class AnalyzerCore
{
private:
thread AnalyzerThread;
void AnalyzerFunc();
bool isRunning;
int id;
public:
AnalyzerCore(int id_in);
~AnalyzerCore();
};
AnalyzerCore.cpp
void AnalyzerCore::AnalyzerFunc()
{
while (isRunning) {
cout << "Analyzer "<< id << " is active!\n";
this_thread::sleep_for(chrono::seconds(1));
}
}
AnalyzerCore::AnalyzerCore(int id_in)
{
id = id_in;
isRunning = true;
AnalyzerThread = thread(&AnalyzerCore::AnalyzerFunc, this);
}
AnalyzerCore::~AnalyzerCore()
{
isRunning = false;
if (AnalyzerThread.joinable()) AnalyzerThread.join();
}
and in the main.cpp, I have maked a vector of AnalyzerCore and push_back 2 instance of the calss
int main()
{
vector<AnalyzerCore> a;
a.push_back(AnalyzerCore(0));
a.push_back(AnalyzerCore(1));
this_thread::sleep_for(chrono::seconds(10));
std::cout << "Hello World!\n";
}
But when I have built above, I have faced following error:
'AnalyzerCore::AnalyzerCore(const AnalyzerCore &)': attempting to reference a deleted function
What's wrong with my code and what do you suggest to fix it? thank you!
You cannot copy a
std::thread(what would that mean?), hence you cannot copy aAnalyzerCore.You can use
std::vector::emplace_back()to construct theAnalyzerCoreobjects directly in the vector, rather than constructing a temporary and then copying or moving it into the vector.Moreover, when the vector grows, it has to reallocate and move or copy elements. As you cannot copy, you need to add a move constructor (when the compiler does not generate it):
Live Demo