SharedPointers.md (1835B)
1 # Shared Pointers 2 3 **Source:** [CPP Reference](https://en.cppreference.com/w/cpp/memory/shared_ptr) 4 5 **Chapter:** N/A 6 7 **Definition:** A shared pointer is a pointer that keeps a reference counter so when the final reference to it goes out of scope, the memory will be freed. 8 9 The value of this is unlike unique_ptr, copies of the pointer can be made. The drawback of this is the overhead both in memory and computation associated with keeping track of the number of pointers that point to the object. 10 11 These should be used when defining your own class to ensure once all pointers to objects of the class type go out of scope, the proper destructor is called. 12 13 An example usage of shared pointers is as follows: 14 15 ```cpp 16 17 #include "iostream" 18 #include "memory" 19 20 class arr{ 21 public: 22 int* array = nullptr; 23 24 ~arr(){ 25 if(array != nullptr){ 26 delete array; 27 } 28 } 29 }; 30 31 std::shared_ptr<arr> getSharedPtr(){ 32 33 auto sharedPtr = std::make_shared<arr>(); 34 int* arr = new int[10]; 35 sharedPtr->array = arr; 36 for(int i = 0 ; i < 10; ++i){ 37 arr[i] = i; 38 } 39 return sharedPtr; 40 } 41 42 int main(){ 43 std::cout << "Testing Shared Pointer" << std::endl; 44 while(true){ 45 std::shared_ptr baseShared = getSharedPtr(); 46 for(int x = 0 ; x < 100 ; ++x){ 47 auto shared = baseShared; 48 for(int i = 0; i < 10; ++i){ 49 std::cout << shared->array[i] << " "; 50 } 51 } 52 std::cout << std::endl; 53 } 54 55 return 0; 56 } 57 58 ``` 59 60 In this usage we call a method to create an integer array allocated on the heap. Since make_shared does not support raw arrays, we encapsulated it in a class. We then return this to the main method and show that we can assign pointers to point at the same memory and do manipulations. We then see since it is an infinite loop, it deallocates memory once the last pointer goes out of scope because otherwise the above code would leak memory.