Modern C++ Learning(8)-Pointers
Pointers
Pointer to Object of Type T
- stores a memory address of an object of type
T - can be used to inspect/observe/modify the target object
- can be redirected to a different target (unlike references)
- may also point to no object at all (be a Null Pointer)

Raw Pointers: T*
- essentially an (unsigned) integer variable storing a memory address
- size: 64 bits on 64 bit platforms
- many raw pointers can point to the same address / object
- lifetimes of pointer and taget (pointed-to) object are independent
Smart Pointers C++11
std::unique_pointer<T> |
- used to access dynamic storage, i.e., objects on the heap
- only one
unique_ptrper object - pointer and target object have same lifetime
std::shared_pointer<T> |
- used to access dynamic storage, i.e., objects on the heap
- many
shared_ptrs and/orweak_ptrs per object - target object lives as long as at least one
shared_ptrpoints to it
nullptr C++11
- special pointer value
- is implicitly convertible to
false - not necessarily represented by
0in memory! (depends on platform)
Coding Convention: nullptr signifies “value not available”
- set pointer to
nullptror valid address on initialization - check if not
nullptrbefore dereferencing
const and Pointers
Purposes
- read-only access to objects
- preventing pointer redirection
Syntax
| pointer to type T | pointed-to value modifiable | pointer itself modifiable |
|---|---|---|
| T * | ✔ | ✔ |
| T const * | ❌ | ✔ |
| T * const | ✔ | ❌ |
| T const * const | ❌ | ❌ |
👉 Read it right to left: “(const) pointer to a (const) T”
The “this” Pointer
- available inside member functions
thisreturns the address of an object itselfthis->can be used to access members*thisaccesses the object itself
class IntRange { |
IntRange r1 {1,3}; // 1 3 |
References
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 王赵安的博客!
评论
