I find myself at a few places in my game wanting to use pointer-to-pointer in my design. For example, I have a class OpenGLRenderer
which creates meshes given vertex/indice/texcoord data, materials given material props, etc. and then a class ResourceManifest
which caches meshes/materials from file and upon loading one of these resources creates an instance of it using the OpenGLRenderer
. So there is a coupling there.
I typically like to employ RAII design when coding which tempts me to the following relationship:
ResourceManifest(OpenGLRenderer** renderer);
Because when the OpenGL context has been torn down and all OpenGL state-specific stuff needs to be reinitialized, such as when recreating the window, I just recreate the OpenGLRenderer
and let the constructor/destructor do all the work and ResourceManifest
using it will never be the wiser.
What I am wondering is if this is enough justification of using plain old pointer-to-pointers, are there any more modern tools or techniques available? I've been looking at various smart_ptrs for example, but they do not deal with the problem at hand, as I want to recreate the managed object without passing out new smart_ptrs.
The reason is that pointers are used to bodge into C some vital features which are missing from the original language: arrays, strings, & writeable function parameters.
Pointers save memory space. Execution time with pointers is faster because data are manipulated with the address, that is, direct access to memory location. Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory as well.
Modern LanguagesThe underlying system behind many modern programming languages still uses pointers but they do not expose the complexity & accessibility of pointers to the programmers.
It is best to avoid using pointers in C++ as much as possible. The use of pointers can lead to confusion of ownership which can directly or indirectly lead to memory leaks.
As others have already stated, you could reference a smart pointer.
However, if you also want to provide functionality beyond smart pointerness you could make your code into an iterator especially if the underlying data structures are not homogeneous. Again, this is a matter of how you'll use your pointer to pointer. Then whatever interface you finally use could itself be wrapped in a smart pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With