I want want to implement a cmmand
class which does some work in an another thread, and I don't want to let users to delete that object manually.My command
class like this:
class Cmd {
public:
void excute() {
std::cout << "thread begins" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2)); // do some work
std::cout << "thread ends" << std::endl;
}
void run() {
// I want std::unique_ptr to delete 'this' after work is done,but does't work
std::thread td(&Cmd::excute, std::unique_ptr<Cmd>(this));
td.detach();
}
// test if this object is still alive
void ok() { std::cout << "OK" << std::endl; }
};
I use it like this:
int main() {
Cmd *p = new Cmd();
p->run();
// waiting for cmd thread ends
std::this_thread::sleep_for(std::chrono::seconds(3));
p->ok(); // I thought p was deleted but not
return 0;
}
As in the comments, the object is still alive after cmd thread finishes, I want to know how to implement such funtionality.
EDIT
users of cmd
does't know when cmd
will finish, so the flowing use case will leads to UB.
std::unique_ptr<Cmd> up(new Cmd); // or just Cmd c;
up->run();
// cmd will be deleted after out of scope but cmd::excute may still need it
CLOSED
I made a mistake about test, in fact the object is deleted after the thread ends.It is more clear with following test with a additional member variable int i
.
#include <functional>
#include <iostream>
#include <stack>
#include <thread>
using namespace std;
class Cmd {
public:
~Cmd() { std::cout << "destructor" << std::endl; }
void excute() {
std::cout << i << " thread begins" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2)); // do some work
std::cout << i << " thread ends" << std::endl;
}
void run() {
// I want std::unique_ptr to delete 'this' after work is done,but it seems
// not working
std::thread td(&Cmd::excute, std::unique_ptr<Cmd>(this));
td.detach();
}
// test if this object is still alive
void ok() { std::cout << i << " OK" << std::endl; }
int i;
};
int main() {
Cmd *p = new Cmd();
p->i = 10;
p->run();
// waiting for cmd thread ends
std::this_thread::sleep_for(std::chrono::seconds(3));
p->ok(); // I thought p was deleted but not
return 0;
}
The flowwing outputs proved the object is deleted.
10 thread begins
10 thread ends
destructor
-572662307 OK
But just as some kind guys suggests, this is not a good design, avoid it as you can.