trying to implement simple ostream singleton class

488 views Asked by At

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

1

There are 1 answers

5
πάντα ῥεῖ On BEST ANSWER

You can't take any std::istream or std::ostream instance by copy, your member variables should be references or pointers:

class OutputData {
    std::fstream* ofile;
    std::ostream* iout;
    static OutputData *odata;
    OutputData(const char* path):iout(nullptr), ofile(nullptr) {
        ofile = new fstream(path);
        if (ofile->is_open()) {
            iout = ofile;
        }
        else {
            delete ofile;
            ofile = nullptr;
            iout = &cout;
        }
    }
    // Take care to provide an appropriate destructor
    ~OutputData() {
        delete ofile;
    }

};

Also regarding your singleton design, I'd rather recommend Scott Meyer's singleton idiom:

class OutputData {
public:
    static OutputData& instance(const char* path) {
        static OutputData theInstance(path)
        return theInstance;
    }
    // Make print a non-static member function
    void print(std::string s) {
        iout << s;
    }
};

Though this approach just weirdly looks exactly like the opposite, as what's considered the canonical solution.