//Make sure to run from the console window//This way you can see the delete message after
//Program end.
//Now I see why so many c++ engines have managers for everything
//I see why they have this extra layer.
//Since I am using MingW, had to add these defines
//if you are using Visual Studio, won't need these
#define WINVER 0x0501
#define _WIN32_WINNT 0x0501
#include "windows.h"
#include <iostream>
#include <stdlib.h>
#include <list>
using namespace std;
class v3
{
private:
int x;
int y;
int z;
public:
v3(int X = 0, int Y = 0, int Z = 0)
{
x = X;
y = Y;
z = Z;
}
void print( void )
{
//tabbing the output so the columns line up
cout << "x:" << x << "\t\ty:" << y << "\t\tz:" << z << "\n";
}
};
// create a vector3 manager to handle dynamic memory for vectors
class v3mngr
{
public:
//will use a STL list container to store the vector3s
list<v3 *> v3List;
v3mngr() {} //empty constructor
// the destructor will free all memory at the end of the program
~v3mngr()
{
list<v3*>::iterator it; //STL iterator, used to go through items
// in a container
for( it= v3List.begin(); it!=v3List.end(); it++ )
{
delete ( *it ); // delete the value pointed to in the list via it
}
v3List.clear(); //finally free memory of the list pointer
cout << "auto deleted pointers" << "\n\n";
}
v3& make(v3* v)
{
v3List.push_back(v);
return *v; //returns the value pointed to by v as a reference
}
};
//Found out about this from Jose's site
// http://www.jose.it-berater.org/smfforum/index.php?topic=775.0
long getAvailbleSystemMemory()
{
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
return status.ullAvailPhys;
}
int main()
{
long startOfApp, after10Vecs, endOfApp;
cout << "startOfApp Available Memory: " << ( startOfApp = getAvailbleSystemMemory() ) << "\n\n";
//our v3 manager that can be used to make and manage dynamic new v3's
v3mngr vm;
int numV3s = 10;
//this was the tricky thing to figure out. how to reference an array
v3 v[numV3s];
v3 (&vr)[numV3s] = v;
for ( int i = 0; i <= numV3s; i++ )
{
vr[i] = vm.make( new v3( rand(), rand(), rand() ) );
vr[i].print();
}
cout << "Memory difference after 10 Vectors created: " << startOfApp - ( after10Vecs = getAvailbleSystemMemory() ) << "\n\n";
cout << "\n\n\n\n";
cout << " Now when the program ends, the memory should be cleaned automatically" << "\n\n\n\n";
cout << " Press Enter to Exit" << "\n\n";
cin.get();
cout << "End System Memory: " << ( endOfApp = getAvailbleSystemMemory() ) << "\n\n";
cout << "End - Start before Pointers Deleted from Memory: " << endOfApp - startOfApp << "\n\n";
return 0; // program ends
// our v3manager destructor gets called here automatically and frees memory
}
Bookmarks