What other scenarios do you think are suitable for using pointers?
One of the main use cases for source pointers is when you have pointers without permissions. Typically, if the link will work, but you want to avoid the limitations of the link (unrealized, not copied). You can use the reference_wrapper type in these cases, but it's easier to just use a raw pointer instead. Smart pointers encode the ownership right (who creates and destroys the object), therefore, if there is no ownership right for encoding (because it is implied otherwise), then the raw pointer is in order.
To make this clear, typical examples of what I just explained are things like:
- temporary copied functors that need a pointer to some object that it does not have.
- internal cross-references in the data structure (for example, "back pointers").
But itβs important to note that these things should not be present in interfaces at all. As a rule, you can completely avoid the use of raw pointers in interfaces (for example, library functions and classes) and use them exclusively inside, that is, in library code, and not in user code. In other words, if you need to use raw pointers, hide them.
Optional pointers are also sometimes visible for optional function parameters, where you can pass nullptr if you don't want this result.
The main thing to avoid and which can be avoided at all is the bare call of new / delete in user code. A typical good modern C ++ library (and even more so with C ++ 11) will not have such exposed new / delete entries and that is a fact.
Source pointers themselves are not a problem, which is problematic: (1) manual memory management and (2) property management (which is problematic if source pointers are used instead of smart pointers).
Would you even recommend learning about pointers in general today?
Of course, you should learn about pointers. They are necessary for understanding programming and learning to write code on the library side. The source pointers are still very present in the guts of a lot of library code, etc., even if you don't see them.
Mikael persson
source share