When I use std::thread to call the function "void createMemoryLeak(const MustP3DPlugin& plugin)", the deconstructor of MustP3DPlugin is called as soon as the thread is finished. I didn't expect this and I was hoping someone could explain to me why this is happening.
#include <Windows.h>
#include <thread>
class MustP3DPlugin {
public:
MustP3DPlugin();
~MustP3DPlugin();
void WaitOneSecond() const;
};
int main() {
MustP3DPlugin plugin = MustP3DPlugin();
}
void createNoMemoryLeak(const MustP3DPlugin* plugin) {
plugin->WaitOneSecond();
}
void createMemoryLeak(const MustP3DPlugin& plugin) {
plugin.WaitOneSecond();
}
MustP3DPlugin::MustP3DPlugin() {
std::thread memoryLeakThread = std::thread(createMemoryLeak, *this);
memoryLeakThread.join();
//~MustP3DPlugin() is called
std::thread noMemoryLeakThread = std::thread(createNoMemoryLeak, this );
noMemoryLeakThread.join();
//but ~MustP3DPlugin() is not called here
}
MustP3DPlugin::~MustP3DPlugin() {
MessageBox(nullptr, TEXT("~MustP3DPlugin()"), TEXT("debug text"), MB_OK);
}
void MustP3DPlugin::WaitOneSecond() const {
Sleep(1000);
}