New blog location
   New blog location  
main calls foo, foo's activation record is at the top of the stack. Once foo returns, the activation record for foo is marked as deallocated, and another function call can make use of that space. Any parameters passed from main to foo are copied into foo's activation record. Below is an illustration for the activation record from Wikipedia:int* pointerToInt;
pointerToInt is currently an uninitialized pointer. Working with unitialized pointers will likely crash the program. One should always initialize pointers. They can be set to null (using nullptr), and checked against null. nullptr converts to false when used in a Boolean expression. Example:if(!pointerToInt) { //execute code that handles null pointer case }
pointerToInt = new int;
*pointerToInt = 42;
delete operator and it is best practice to then set the pointer to nullptr:delete pointerToInt; pointerToInt = nullptr;
& or address-of operator:double k = 42.0 double* kPtr = &k;
Person * person = getPerson(); double address = (*person).address;
(*ptr). notation and it is the arrow notation. The same code can be written as follows:Person *person = getPerson(); double address = person->address;
bool hasValidAddress = (person && person->address != "")
new[] operator as follows:int arySize = 10; int* ptrToDynamicAry = new int[arySize];
delete[] ptrToDynamicAry ptrToDynamicAry = nullptr;
std::unique_ptr and std::shared_ptr are the most commonly used and defined in the <memory> header file. unique_ptr is similar to a raw pointer but automatically frees the memory after it goes out of scope or is deleted. unique_ptr is the sole owner of the object it points to. Even when an exception is thrown, the memory pointed to by the unique pointer is deallocated. The syntax for a unique_ptr is as follows:auto person = std::make_unique<Person>();
std::unique_ptr<Person> person(new Person);
unique_ptr can be used similar to a normal pointer as it overloads the arrow operator (->) and the indexing operator ([]).unique_ptr:auto myAry = std::make_unique<int>(10); cout << "Integer at position 5 is " << myAry[4] << endl;
Comments
Post a Comment