Hi,
First up, note that all of what I am about to say falls into the category of: Most of the time it's not advised to do these things, but there are some circumstances where experts do have a need for them. Some other things that fit into the same category are: globals,
goto
.
The big question here for me is: Why are you using pointers /
new
/
delete
with C++ at all? See below about C programming.
IMO, there is no need for any of those in modern C++, in fact they
create problems. Namely code not reaching a
delete
because of an exception. This is beside forgetting to match the
new
and
delete.
Instead,
so much can be done with the STL containers: The memory management is done, there is bounds checking, and heaps of other really helpful facilities such as the algorithms. References are also a big thing, they are better than a raw pointers.
With polymorphism, it needs a container of pointers, but one can't directly have a container of references, so there is
std::reference_wrapper
to achieve this. It essentially wraps a reference in a pointer.
This all comes about because of the evolution of the languages. In C there was
malloc
and
free
, then C++ eventually had
new
and
delete
. Then the problems with those became apparent, so it was better to use smart pointers. Smart pointers had been around for awhile, and it turned out they were a better solution. But even better was the STL, which is designed to work properly and do the right thing in various situations.
The trouble is that lots of teachers, lecturers and authors
still teach
new
&
delete
.
C++ also has move semantics and perfect forwarding, so in certain circumstances one can use pass by value where a move constructor is available or copy elision is employed by the compiler.
There is heaps of good stuff to read here, unfortunately the internal links don't work:
C Progamming
This is where pointers are used a lot, but be aware C is a whole different mindset. Many of the bells & whistles that come with C++ aren't there in C: You will find yourself being responsible for doing all kinds of checking. Especially diligence with initialisation, bounds checking, detailed knowledge of how library functions work and
const
correctness to name a few.
So if you are keen to learn about pointers, try doing it with C, rather than using
new
&
delete
- which just leads to bad c++ habits IMO.