oop - errors when trying to pass an ofstream to an object (C++) -
i'm writing branch predictor simulator architecture class , i'm having trouble getting output working between multiple classes. i'm trying open 1 main ofstream in main.cpp , pass constructor of each class use objects. i'm getting whole bunch of errors in header file such as:
in file included main.cpp:4:0: predictors.h: in constructor â?~atpred::atpred(std::ofstream&)â?t: predictors.h:14:18: error: use of deleted function â?~std::basic_ofstream<char>& std::basic_ofstream<char>::operator=( const std::basic_ofstream<char>&)â?t so errors seem in header file:
#ifndef predictors_h #define predictors_h #include <string> // taken class atpred{ private: std::ofstream outputfile; public: // constructor atpred(std::ofstream& file) { outputfile = file; } // deconstructor ~atpred() {} // member functions void parseresults(std::string filename); }; // non-taken class antpred{ private: std::ofstream outputfile; public: // constructor antpred(std::ofstream& file) { outputfile = file; } // deconstructor ~antpred() {} // member functions void parseresults(std::string filename); }; #endif i'm not sure i'm going wrong here, appreciated.
the problem here you're storing ofstream value rather reference. can make code work changing antpred (and changing atpred) follows:
class antpred { private: std::ofstream &outputfile; public: antpred(std::ofstream &file) : outputfile(file) { // other construction work } }; while make code work, not safe. storing reference ofstream object implicitly assumes outlive atpred , antpred instances. if ostream destroyed first, behavior of atpred , antpred instances undefined , lead segfaults.
a non-exhaustive list of other options include using raw pointers (leads same lifetime issues pointed out above), shared pointers (either c++11 std::shared_ptr, boost::shared_ptr or other shared pointer library), constructing separate output stream each object, or passing output stream object instances when required log data.
Comments
Post a Comment