Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to pointer-to-pointers in C++?

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.

like image 881
KaiserJohaan Avatar asked Jul 31 '13 21:07

KaiserJohaan


People also ask

Why pointers are not used in C?

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.

Is it better to use pointers in C?

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.

Do people still use pointers?

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.

Should pointers be avoided?

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.


1 Answers

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.

like image 154
Cos314 Avatar answered Oct 15 '22 13:10

Cos314