#include #include #include #include #include "Example.h" using namespace std; //-------------------------------------- // The mainline/app. // All this one tries to do is to show // when destruction take place. //-------------------------------------- Example sub(Example ex) { return ex; } int main(int argc, char* argv[]) { // Here's a local object. It will be deleted when we leave // this scope. cout << "\nLocal object:" << endl; Example local("local"); // Here we new up an object. To delete it, we use 'delete'. cout << "\nnew'ed object:" << endl; Example *scalarEx = new Example("new'ed"); delete scalarEx; // Arrays... //-------------------------------------------------------------------- // We'd like to new up an array of objects. // (Note: These dosn't work, and there's no simple way to make it work.) Example arrayEx[10]; Example *ptrArrayEx = new Example[10]; //-------------------------------------------------------------------- // This is one (awkward) way around the problem. cout << "\nArray of objects:" << endl; Example **arrayEx = new Example*[5]; for ( int i=0; i<5; i++ ) { arrayEx[i] = new Example( string( to_string(i) ).c_str() ); } for ( int i=0; i<5; i++ ) { delete arrayEx[i]; } delete [] arrayEx; // Here are automatic variabless: created in a local scope and // destroyed on exit from that scope. { cout << "\nShort-lived local:" << endl; Example localEx("short-lived local"); } // Here's the most complicated example, and one that's surprisingly // hard to get right. cout << "\nFunction call, return, assign:" << endl; Example returnedVal = sub(local); }