Shared Pointer A shared pointer is a smart pointer that allows for distributed ownership of data. Each time it is assigned, a reference count is incremented, indicating one more owner of the data. When the pointer goes out of scope or an owner calls reset , the reference count is decremented. When the reference count goes to 0, the data pointed to is deallocated. Use make_shared : auto person = std :: make_shared < Person > ( ) ; if ( person ) { cout << "Person's address is " << person -> address ; } C++17 allows use of shared pointers to point to dynamically allocated arrays. However, make_shared cannot be used. Below is an example: shared_ptr < Person [ ] > persons ( new Person [ 10 ] ) ; persons [ 0 ] . _name = "Jack Sparrow" ; persons [ 0 ] . _address = "Caribbean" ; cout << "Address of first person " << persons [ 0 ] . address << endl ; A better solutio...
C-style strings C style strings should be avoided except when interfacing with C libraries. C string library functions provide no bounds checking and memory allocation support. They are represented as an array of characters. Last character of the string is the null character \0 , so that code that uses the string knows where it ends. The space needed for a string is always one more than the number of readable characters. String Literals Strings written with quotes around them are string literals. They are stored in a read-only part of memory. Because they are stored in readonly sections, attempting to modify string literals is undefined behavior . Example: char * str = "world" ; str [ 0 ] = 'y' ; //undefined behavior If the code respected the standard and assigned the string literal to const char* , the compiler will catch attempts to modify string literals: const char * str = "world" ; str [ 0 ] = 'k' ; //compiler will f...
Pointers and Dynamic Memory Dynamic memory is useful when you don't know the memory requirements at compile time. Stack and the Heap Memory is divided into the stack and the heap or free store . Stack memory is automatically managed, whereas heap memory is not. Activation Records are blocks of memory on the stack that are used to implement functions. For example, when 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: Memory allocated on the heap lives indepedently of the function calls. Once has to make sure to deallocate memory allocated on the heap. Some language...
Comments
Post a Comment