Question
Is it safe to move object inside its destructor
I'm 99% sure the answer to my question is 'Yes'. I just want to double check my assumption is right and I want to be sure that there is nothing in the upcoming C++ standards that could change the rules (like destructive move if it is really possible).
So, my case is as following. I have an object of the Request
type whose lifetime is managed by std::shared_ptr<Request>
. When the object is about to die (i.e. the ref counter is zero and std::shared_ptr
is calling the ~Request
destructor) I need to check some condition and create another instance of the Request
type with exactly the same data. Basically I just need to prolong the subscription.
The cheapest way from my point of view is just to call the move ctor of the Request
class:
Request::~Request()
{
if(condition)
{
service.subscribe(std::make_shared<Request>(std::move(*this)));
}
}
As far as I know all data members of the Request
instance in the context of destructor are still alive. They are not destroyed yet. So it has to be safe to move them somewhere, right? Is my assumption in line with the idea of C++ and I'm not doing anything stupid?
Related questions: