L
Leo \Equinox\ Gaspard
Maybe some idea could be to use in the class a pointer to a shared_ptr to itself, and expose read-only access to it, or return it in the factory.
Then, as you use commit_suicide_when_done (or whatever you called it), you could just delete the pointer to shared_ptr, and then it means "I'm ready to be deleted". So, as soon as the user allows deletion of the object by deleting the last copy of the shared_ptr he created, the object will be deleted by the shared_ptr destructor.
I mean :
class Suicide
{
std::shared_ptr<Suicide> * myself_;
public:
Suicide() : myself(this) { }
std::shared_ptr<Suicide> myself() { return *myself_; }
void commit_suicide_when_done() { delete myself_; }
};
Then, using it as :
Suicide * s = SomeFactory::createSuicide();
// I want to use s after its deletion, I *don't* want it to be deleted
std::shared_ptr<Suicide> o = s->myself();
o->commit_suicide_when_done();
// And, now, I *do* agree it to be deleted, as I used it some times
delete o;
I'm not sure whether my implementation is correct, but I think it could be an idea.
Best,
Leo
Then, as you use commit_suicide_when_done (or whatever you called it), you could just delete the pointer to shared_ptr, and then it means "I'm ready to be deleted". So, as soon as the user allows deletion of the object by deleting the last copy of the shared_ptr he created, the object will be deleted by the shared_ptr destructor.
I mean :
class Suicide
{
std::shared_ptr<Suicide> * myself_;
public:
Suicide() : myself(this) { }
std::shared_ptr<Suicide> myself() { return *myself_; }
void commit_suicide_when_done() { delete myself_; }
};
Then, using it as :
Suicide * s = SomeFactory::createSuicide();
// I want to use s after its deletion, I *don't* want it to be deleted
std::shared_ptr<Suicide> o = s->myself();
o->commit_suicide_when_done();
// And, now, I *do* agree it to be deleted, as I used it some times
delete o;
I'm not sure whether my implementation is correct, but I think it could be an idea.
Best,
Leo