mercredi 18 décembre 2019

What is the practice for handling a complex resource pointer in C++ when allocating a new version of the resource?

In most of my programming now a day I put everything in a smart pointer and forget about it. The resource is properly managed 99.9% of the time. It's really great and way better than a garbage collection mechanism.

However, once in a while, the resource being held by a smart pointer needs to be explicitly freed before we can reallocate a new instance of it. Something like this:

r = std::make_shared<my_resource>(with_this_id);

r->do_work();
...
r->do_more_work();
...
r->do_even_more_work();

r->reset();

r = std::make_shared<my_resource>(with_this_id);

...

If I miss the r->reset() call, the resource may either be using a large mount of memory or disk space and re-allocating without first resetting is likely to cause problems on smaller computers. Either that, or the resource is locked so it can't be reallocated until explicitly freed.

Is there a pattern/algorithm/something which handles such a case in a cleaner manner?

Aucun commentaire:

Enregistrer un commentaire