A pointer is a variable that stores the memory address of an object. Pointers are used extensively in both C and C++ for three main purposes:
- to allocate new objects on the heap,
- to pass functions to other functions
- to iterate over elements in arrays or other data structures.
In C-style programming, raw pointers are used for all these scenarios. However, raw pointers are the source of many serious programming errors. Therefore, their use is strongly discouraged except where they provide a significant performance benefit and there is no ambiguity as to which pointer is the owning pointer that is responsible for deleting the object. Modern C++ provides smart pointers for allocating objects, iterators for traversing data structures, and lambda expressions for passing functions. By using these language and library facilities instead of raw pointers, you will make your program safer, easier to debug, and simpler to understand and maintain. See Smart pointers, Iterators, and Lambda expressions for more information.
In this section
- Raw pointers
- Const and volatile pointers
- new and delete operators
- Smart pointers
- How to: Create and use unique_ptr instances
- How to: Create and use shared_ptr instances
- How to: Create and use weak_ptr instances
- How to: Create and use CComPtr and CComQIPtr instances