// Native_SmartPointers.cpp : Defines the entry point for the console application. /* ______________________________________________________________ U S I N G S M A R T P O I N T E R S Ron Kessler Created 1/9/2017 Native version Purpose: Here we learn about unique_ptr. This is used as a pointer to an object but the destructor for the object is called automatically. This way, we never have to use the new or delete keywords with creating plain pointers. So we get the advantage of creating objects on the heap but without the hassle of forgetting to release those resources! Look at the Employee.h file to see the structure of the Employee class. Run with CTL-F5 ______________________________________________________________ */ #include "stdafx.h" #include "Employee.h" #include #include //so we can use std::unique_ptr using namespace std; void createEmployee (); //framework for function int main() { createEmployee (); return 0; } void createEmployee () { try { //---now create two new Employees. Employee HR{ "Grace" }; //no pointer just an object on the heap //---now use a smart pointer to create another Employee on the heap. We would do // this if we needed to access this object in another part of our app or we needed // it to remain in memory when a function goes out of scope. std::unique_ptr smartPtr{ new Employee{ "Charlie" } }; //---now lets say there is an error and the app needs to cleanup these objects throw ( exception{ "Another error by Ron!" } ); } catch (const exception& e) { cout << "Exception was caught: " << e.what () << "\n\n"; } cout << "Notice how the objects are destroyed in the reverse order they were created! \n\n\n"; }