Re : Force creation of objects with new operator

  • Thread starter Leo \Equinox\ Gaspard
  • Start date
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top