// demonstration of common memory leak #include #include #include #include using namespace std; const double conv = 45.0/atan(1.0); class GPScoords { public: GPScoords() { cout << "made GPS coords @ " << this << endl; } ~GPScoords() { cout << "del GPS coords @ " << this << endl; } void load(istream &is) { is >> lat >> lon; lat /= conv; lon /= conv; } void save(ostream &os) const { os << lat*conv << ' ' << lon*conv; } double distance(const GPScoords &gps) const { // in km // this assumes the Earth is a sphere -- much better formulae exist return acos(sin(lat)*sin(gps.lat) + cos(lat)*cos(gps.lat)*cos(lon-gps.lon))*6371.0; } private: double lat, lon; }; // find distance between next two GPS coords in file double dist(istream &s) { GPScoords first,second; first.load(s); second.load(s); return first.distance(second); } int main(int argc, char **argv) { fstream file; file.exceptions(ifstream::eofbit); try { file.open(argc>1 ? argv[1] : "testgps.txt"); cout << dist(file) << " km" << endl; } catch (std::exception e) { cout << "file not properly formatted" << endl; } }