SmartPtrp(new int(42)); // create a SmartPtr object controlling a new integer int x = *p; // access the integer through the SmartPtr object std::cout << x << std::endl; // print the value of the integer (42)
SmartPtrarr(new int[5]); // create a SmartPtr object controlling a new array of integers arr[0] = 1; // initialize the first element arr[1] = 1; // initialize the second element for (int i = 2; i < 5; i++) { // compute the remaining elements arr[i] = arr[i-1] + arr[i-2]; } for (int i = 0; i < 5; i++) { // print the elements std::cout << arr[i] << ' '; } std::cout << std::endl; // print a newline
SomeResource* resource = new SomeResource(); // allocate a resource using a third-party library SmartPtrIn these examples, SmartPtr is used to manage the memory of dynamically allocated objects, including arrays and resources from third-party libraries. By ensuring that memory is deallocated when it is no longer needed, SmartPtr helps prevent memory leaks and other memory-related bugs.p(resource); // wrap the resource in a SmartPtr object p->do_something(); // use the resource through the SmartPtr object // ...