#include "Car.hpp" #include "Truck.hpp" #include "Logger.hpp" #include "VehicleFactory.hpp" #include #include void workOnCopy_naive(std::vector vehicles){ std::vector tempVec; for (int i=0; i(currentVehicle); // RTTI type check Truck* truckToCopy = dynamic_cast(currentVehicle);// may be nullptr if(carToCopy){ tempVec.push_back(new Car(carToCopy->model(), carToCopy->maxWeight())); // type dependency to Car }else if(truckToCopy){ tempVec.push_back(new Truck(truckToCopy->model(), truckToCopy->payload_kg())); // type dependecy }else{ // TODO: what do we do here? // Did someone add a new class to the code base? return; // BUG: copies aren't free'd } } // work on copies ... // ... for(auto vehi : tempVec){ std::cout << vehi->model() << " " << vehi->payload_kg() << " kg" << std::endl; } for (int i=0; i vehicles){ // uses RAII, virtual ctor class RAIIvector { // local RAII helper class public: std::vector tempVec; ~RAIIvector(){ for(auto vehi : tempVec){ delete vehi; } tempVec.clear(); } }; RAIIvector rv; for(auto vehi : vehicles){ rv.tempVec.push_back(vehi->clone()); } // work on copies ... // ... for(auto vehi : rv.tempVec){ std::cout << vehi->model() << " " << vehi->payload_kg() << " kg" << std::endl; } // compiler WILL invoke RAIIvector::~RAIIvector() here } int main(int argc, const char * argv[]) { std::vector vehicles; vehicles.push_back(vehicleForPayload("Volkswagen Golf", 900)); // use factory for construction vehicles.push_back(vehicleForPayload("Magirus Deutz", 18*1000)); Logger::getInstance()->log("work naively", __FILE__, __LINE__); workOnCopy_naive(vehicles); Logger::getInstance()->log("work smartly", __FILE__, __LINE__); workOnCopy_smart(vehicles); return 0; }