SimplifyC++ Article
Pointers in Modern C++
Pointers in Modern C++
A pointer is an object that stores the address of another object or function. Unlike a reference, a pointer is itself a separate object with its own value.
Basic pointer declaration
int main() { int value{10}; int* ptr = &value;
std::cout << value << '\n'; std::cout << *ptr << '\n';}Here:
&valuemeans “the address ofvalue”,ptrstores that address,*ptrmeans “the object pointed to byptr”.
Address-of and indirection
Two operators are fundamental:
&gives the address of an object,*dereferences a pointer to access the pointed-to object.
int value{7};int* ptr = &value;
int copy = *ptr;Changing an object through a pointer
int main() { int value{10}; int* ptr = &value;
*ptr = 99;
std::cout << value << '\n'; // prints 99}Pointers can be reassigned
Unlike references, pointers can be changed to point somewhere else.
int main() { int a{10}; int b{20};
int* ptr = &a; std::cout << *ptr << '\n'; // 10
ptr = &b; std::cout << *ptr << '\n'; // 20}Pointers can be null
A pointer can intentionally point to nothing.
int* ptr = nullptr;This is one of the major differences between pointers and references.
Pointers to dynamic objects
Pointers are often associated with dynamic allocation:
int* ptr = new int(42);delete ptr;This is valid C++, but Modern C++ strongly discourages using raw owning pointers as a beginner's default style. Later chapters will show why smart pointers are usually better.
Pointers are objects too
A pointer itself has storage, a type, and a value.
int value{5};int* ptr = &value;Here:
valueis anintobject,ptris anint*object,the value stored in
ptris an address.
What did you think?
Sign in to react or comment.
Comments
0No comments yet.