Why pointers are important |
Why are array indices important?
Pointers are just another way for your program to express
indirection -- in other words, to access something without using it's name. You use indirection when accessing some element of an array:
my_array[22];
.
So in a way, pointers are a bit like array indices. But they're more versatile, since you don't need to have an array around to use them. They let you access things that your program doesn't own, or needs to share between programs or between modules of the same program.
Suggestions:
-- Initialize your pointer to
nullptr
(prefer this over
NULL
since C++11)
-- Once the pointed to resource is dead, set your pointer to
nullptr
.
-- Keep track of the owner of the pointed-to-resource
Rules:
-- Make sure the pointed-to resource is alive when you access it;
-- Follow the
strict pointer aliasing rules.
Maybe there's more but I can't remember.
Note:
In modern C++ (since 2011) there are two standard facilities called
unique_ptr
and
shared_ptr
, AKA "smart pointers". You should be using these, instead. They're a little bit more complicated, but much harder to break.
Note:
Please avoid writing "C/C++" again. C is not interchangeable with C++, and the differences between the languages are only increasing with time. Best practice in C is not the same thing as best practice in C++. The above note describes one such difference.