UniquePointers.md (1429B)
1 # Unique Pointers 2 3 **Source:** [CPP References](https://en.cppreference.com/w/cpp/memory/unique_ptr) 4 5 **Chapter:** N/A 6 7 **Definition:** A unique pointer in c++ is a pointer that can not be copied and once out of scope, automatically deallocates associated memory. 8 9 The value of this is that unlike shared pointers, it does not have any overhead beyond normal pointers. Additionally, once it goes out of scope, the memory is managed automatically. This is useful because we can then return things from a method and not have to worry about deallocation of the memory afterwards. An example of this is shown below: 10 11 ```cpp 12 13 #include "memory" 14 #include "iostream" 15 16 std::unique_ptr<int[]> genPtrToArray(){ 17 // the <int[]> portion of the left side is optional. 18 std::unique_ptr<int[]> unique = std::make_unique<int[]>(42); 19 for(int i = 0; i < 42; ++i){ 20 unique[i] = i; 21 } 22 return unique; 23 } 24 25 int main(){ 26 std::cout << "Testing unique pointers."<< std::endl; 27 28 std::unique_ptr<int[]> ptr = genPtrToArray(); 29 for(int i = 0 ; i < 42; ++i){ 30 std::cout << ptr[i] << " "; 31 } 32 std::cout << std::endl; 33 return 0; 34 } 35 36 ``` 37 38 In the above code, it is evident that we don't need to call delete despite calling new in the function and by running this code we can verify that the int array allocated in memory does not get deallocated after being returned from the method because we are still able to print out the numbers 0-41 in the main method.