I'm a backend programmer by trade, and mostly we read input, allocate memory, do our calculations, write output, and throw everything away. Smart pointers never come up. But now it's time to come out of my shell (pun intended).
I've read all the things about smart pointers, and I can rattle off answers to the questions of when use them and how. (A few references: Smart pointer (Wikipedia), Smart Pointers (Modern C++) (Microsoft), C++11: Replace all non-owning raw pointers with std::shared_ptr()? (Stackoverflow))
I've seen everyone's website that shows a trivial example of a smart pointer and I've written my own as well. I know how to break chains with weak pointers. (But why would anyone write their own linked list instead of using an STL container? To have a heterogeneous collection?)
In every example I've seen, there is no possible argument that makes smart pointers a better choice than local or member variables and stack allocation. None of them explain a non-trivial example of a need for smart pointers.
I want to know a problem setup and a decision tree that leads a reasonable programmer to choose to implement smart pointers. And I want to see an implementation of it in less than a couple hundred lines.
It doesn't have to be the best choice, or the only choice, and the choice can be constrained by legacy decisions. But example must NOT be easily--and safely!--implemented without smart pointers.
(Possibilities: managing an active list from a worker pool, networking resources, whatever.)
The implementation will be utterly minimal, and that's fine. The accompanying decision tree will reveal why smart pointers are the right choice. (For example, perhaps there is a place in the code where common mistakes lead to memory errors. Perhaps an STL container disallows certain flexibility. Explain those decisions.)
But please tell me exactly why the example should not be rewritten to use local or member variables; or why it's inappropriate to throw the pointers or pointed-to objects into a container, and make some overarching containing object responsible for deallocation.
Aucun commentaire:
Enregistrer un commentaire