I want to implement a singleton class that receives file path as a parameter. I tried to write the following code . I know it doesn't work and not good but I can't find why..
class OutputData {
std::fstream ofile;
std::ostream iout;
static OutputData *odata;
OutputData(const char* path):iout(std::cout), ofile(path) {
if (ofile.is_open()) {
iout = ofile;
}
}
public:
static void print(std::string s) {
iout << s;
}
};
in .cpp
OutputData *OutputData::odata = nullptr;
and from now on I want that every class will have the ability to write to that stream.
thanks
You can't take any
std::istream
orstd::ostream
instance by copy, your member variables should be references or pointers:Also regarding your singleton design, I'd rather recommend Scott Meyer's singleton idiom:
Though this approach just weirdly looks exactly like the opposite, as what's considered the canonical solution.