Should I use pointers all the time in C++?

C++ Programming

Contrary to most answers here, I have no particular aversion to pointer implementations in C++.

To me, a pointer is just a variable. So saying ‘pointers are bad’ is saying variables are bad. After all it is really just an unsigned integer that contains an address and has a type associated with it.

An indirect reference serves a purpose. It allows access without copying and replacing values and allows objects to cross context boundaries. Of course the possibility of abuse and error is present in such situations, but it always is anyway really. Any variable can contain a bad value, be it a pointer or a direct variable.

C++ has some tricks up its sleeve with references, lvalue references, smart casting, etc, that do indeed make for safer code constructs when indirection and pass-by-reference is used — which is all the time. Of course it is encouraged to use these tools to write more robust and reusable code.

But it is not altogether possible to avoid pointer implementations in a lot of situations, so to be ‘afraid’ or revulsed by them is to throw away some essential programming tools.

Look into the STL and you will find a lot of pointer stuff in there.

Almost any time you need to interface with C code you are going to be passing pointers around. You have to; that’s how C operates on anything more complicated than a primitive value.

Most of the STL library utilities and object have pointer-return and pointer-parameter functions for this purpose.

“Never Use Pointers” is like saying “Never Peel Oranges and Never separate orange into slices — the only way is to chomp down, peel and all. After all , raw orange internals are delicate and you could break them and leak juice all over!”

You learn how to safely use pointers and when there are better ways to get a job done (and when there aren’t). If you are not comfortable with pointers and how to use them, then that is a hole in your education, not a good thing. If you must abstract your programs up and away from memory locations and allocation and referencing, well then perhaps a hardware-facing, compiled systems language that is a super-set of the C language is not the language you should be learning.

That is not to say refactoring out raw pointers is not necessary or preferable in a lot of cases. The additional mechanisms for indirection and referencing in C++ over C are there to help facilitate safer code and they should be used, preferred, and leveraged to the hilt.

Works at khk MATLAB solution(2020-present)