C++ Pointers 👷🏼♂️👷🏼♀️
(from ⇛ Javidx9's youtube video)
Operators
& is the address of operator
int SomeArray[10];
int* pLocation0 = &SomeArray[0];
int* pLocation3 = &SomeArray[3];
However SomeArray is a pointer in disguise (yeah, it's like a transformer 😉), so we can write...
int* pLocation0 = SomeArray; // SomeArray is the same as &SomeArray[0]
* is the value of operator
plocation0
holds a memory address
*pLocation0
gives the value at that memory location.
cout << pLocation0 << endl; // displays the memory location where SomeArray is
cout << *pLocation0 << endl; // displays the contents of the memory location
NOTE: pointers of type char
are handled slightly differently (as they were handled as strings, historically)
Local Variables are created on the stack
Variables created with new
or malloc
are created on the heap, and MUST be released afterwards.
Pointers to pointers
sSomeObject **pSomeObject = new sSomeObject* [10] {0};
This creates an array of pointers, the pointers themselves don't point to anything. The code fragment {0}
at the end of the line fills the pointers with 0.
NEED TO DOUBLE CHECK THE FOLLOWING it can be found around index 25:00 in the javidx9 video.
When an array of pointers is populated with objects, need to remember to delete the created objects and then delete the array.
for (int i=0; i<10; i++) pSomeObject[i] = new SomeObject();
// do stuff
// delete objects
for (int i=0; i<10; i++) delete pSomeObject[i];
delete [] pSomeObject;
Arrays of pointers like this are very useful as pointers are a key method of using polymorphism within C++.
Smart Pointers (since C++ 11)
Use unique and shared pointers to automatically release allocated space.
shared pointers
shared smart pointers allow multiple accessors to a pointer
#include <memory>
// declaring and instantiating an object with a smart pointer
// () at the end is the ctor
shared_ptr<SomeObject> pObj1 = make_shared<SomeObject>();
// sharing the pointer
shared_ptr<SomeObject> pObj2 = pObj1;
Shared pointers keep a reference count of how many times they have been shared (and that those additional pointers are in scope). When this count hits zero the resources pointed to are released.
unique pointers
Very similiar to shared pointers with the exception that the pointer cannot be assigned to another pointer. It can however be transferred to another unique pointer.
Unique pointers have the same memory footprint as pointers.
#include <memory>
// declaring and instantiating an object with a unique pointer
unique_ptr<SomeObject> pObj1 = make_unqiue<SomeObject>();
// sharing the pointer - this is illegal
unique_ptr<SomeObject> pObj2 = pObj1;
// transferring the pointer (transferring ownership of the data)
unqiue_ptr<SomeObject> pObj3 = std::move(pObj1);
Unique pointers can be passed as arguments using references.
void MyFunc(const std::unique_ptr<SomeObject>& pObj) {
// do something with pObj here
std::cout << pObj->field << endl;
}