Creating an Array Using a Smart Pointer
#include <iostream> #include <memory> using namespace std; // Print the contents of the array backwards. void prback(unique_ptr<int[]> &arr, int size) { cout << "----------------------------------------------------" << endl; for(int i = size-1; i >= 0; --i) cout << arr[i] << " "; cout << "\n----------------------------------------------------" << endl; } int main() { // Allocate an array dynamically with new. This is the only // standard way to allow the size to be a variable, though gcc will // variable-sized regular arrays as an extension. Ask for the // size, then allocate. int size; cout << "How big would you like that array, sir? "; cin >> size; unique_ptr<int[]> arr(new int[size]); // Interestingly, // unique_ptr<int> arr(new int[size]); // will compile, but then arr[i] won't. // Read it in. for(int i = 0; i < size; ++i) cin >> arr[i]; // Print it out backwards (using a function). prback(arr, size); }