Memory allocated for new, is deallocated automatically when thread joins main thread or I must deallocated them using delete()
Here is the example code,
#include <iostream>
#include <thread>
using namespace std;
class thread_obj {
public:
void operator()(int x)
{
int* a = new int;
*a = x;
cout << *a << endl;
}
};
int main() {
thread th1(thread_obj(), 1);
thread th2(thread_obj(), 1);
thread th3(thread_obj(), 1);
thread th4(thread_obj(), 1);
// Wait for thread t1 to finish
th1.join();
// Wait for thread t2 to finish
th2.join();
// Wait for thread t3 to finish
th3.join();
while (true) {
// th4 is still running
/* whether the memory allocated for (int* a = new int;) is freed automatically when thread 1, 2, 3 joins main thread
Does this cause memory leak or I must delete them manually?*/
}
th4.join();
return 0;
}
Memory allocated for new int in th1, th2, th3, th4.
After joining (th1, th2, th3) in main thread, are they deallocated automatically and free to use for th4?
Thanks in advance.